连接关闭异常即使它是打开的

问题描述 投票:0回答:0

我的存储库中有以下方法:

public async void UpdateName(int id, string name)
{
    var connection = dataContext.GetDatabase().Connection;
    var initialState = connection.State;

    try
    {
        if (initialState == ConnectionState.Closed)
            await connection.OpenAsync();

        await connection.ExecuteAsync("myproc", new { id, name}, commandType: CommandType.StoredProcedure);
    }
    catch
    {
        throw;
    }
    finally
    {
        if (initialState == ConnectionState.Closed)
            await connection.CloseAsync();
    }
}

调用

Connection is closed
时抛出异常
ExecuteAsync
。在调用之前调试代码并检查连接状态时,状态为
Open
.

此外,我正在查看

ExecuteAsync
实现,我看到该方法也尝试打开连接。

所以我的问题是:

  1. 为什么会抛出异常?
  2. 我可以删除我的方法中的打开/关闭连接吗?

更新

这是堆栈跟踪:

在 System.Data.SqlClient.SqlCommand.EndExecuteNonQuery(IAsyncResult >asyncResult) 在 >System.Threading.Tasks.TaskFactory

1.FromAsyncCoreLogic(IAsyncResult >iar, Func
2 endFunction, Action
1 endAction, Task
1 promise, Boolean >requiresSynchronization) --- 从上一个位置开始的堆栈跟踪结束 --- 在 Dapper.SqlMapper.d__39.MoveNext() 在 >C:\myapp\myrepository.cs:line 91 中的 MyApp.MyRepository.d__5.MoveNext() 在 System.Threading.Tasks.Task.<>c.b__128_1(Object >state) 在 System.Threading.QueueUserWorkItemCallback.Execute() 在 System.Threading.ThreadPoolWorkQueue.Dispatch() 在 System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()

c# dapper
© www.soinside.com 2019 - 2024. All rights reserved.