Async inside Using block

后端 未结 1 1013
情歌与酒
情歌与酒 2021-01-01 18:41

I have the following async function in C#:

private async Task CallDatabaseAsync(Func> execAsync)
{
    u         


        
相关标签:
1条回答
  • 2021-01-01 18:50

    In ASP.NET, each request has a special SynchronizationContext. This synchronization context makes the code that runs after the await use the same "context" of the original request. For example, if the code after the await accesses the current HttpContext, it will access the HttpContext that belongs to the same ASP.NET request.

    When a request terminates, the synchronization context of that request dies with it. Now, when the asynchronous database access completes, it tries to use the SynchronizationContext that it captured before the await to run the code after the await (which includes the code that disposes of the SQL connection), but it cannot find it anymore because the request has terminated.

    What you can do in this case is make the code after the await not depend on the current ASP.NET request's SynchronizationContext, but instead run on a Thread-pool thread. You can do this via the ConfigureAwait method like this:

    private async Task<T> CallDatabaseAsync<T>(Func<SqlConnection, Task<T>> execAsync)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            return await execAsync(connection).ConfigureAwait(false);
        }
    }
    
    0 讨论(0)
提交回复
热议问题