0

I am trying to get my head around ConfigureAwait(false) and came across this https://devblogs.microsoft.com/dotnet/configureawait-faq/ From what I understand, and please correct me if I am wrong, is that ConfigureAwait(false) should be used when we are NOT sure of the calling SynchronizationContext's queuing capacity for tasks, or a potential for a deadlock.

We have asp dotnetcore project where we expose few endpoints for CRUD operations on certain functionality. In the database layer of this project, I came across code like:

public async Task<SomeType> CreateItemAsync(Item item, DateTime startDate, DateTime endDate)
{
    await using var connection = SqlConnection.GetConnectionAsync();
    try
    {
        var item = await connecion.QueryAsync<int>(....).ConfigureAwait(false);
        if(item == null)
        {
            throw new DatabaseException($"failed to insert item");
        }

        var subItemsTasks = new List<Task<int>>();
        subItemsTasks.Add(connection.QueryAsync(...)); //subItem1
        subItemsTasks.Add(connection.QueryAsync(...)); //subItem2
        subItemsTasks.Add(connection.QueryAsync(...)); //subItem3
        ...
        ...

        await Task.WhenAll(subItemsTasks).ConfigureAwait(false);
        return await connection.QueryAsync<int>(...).ConfigureAwait(false);
    }
    catch (Exception e)
    {
        throw new DatabaseException(...);
    }
}

Is this a good pattern to implement? Also, do we need ConfigureAwait(false) on Task.WhenAll() when it is already called on a different synchronization context than original. Same for the return statement configure await.

Monku
  • 2,440
  • 4
  • 33
  • 57
  • You're right about when to use ConfigureAwait(false). In the code shown, there's one missing on the very first await statement. _"when it is already called on a different synchronization context than original"_ ...what makes you say that? How are the statements you mentioned any different to any of the other awaited methods? – ADyson Jan 18 '21 at 23:57
  • 2
    "when it is already called on a different synchronization context than original" - [`async` has a "fast path"](https://blog.stephencleary.com/2012/02/async-and-await.html) which means you can't **know** it's on a thread pool context. Either use `ConfigureAwait(false)` for every `await` in a method, or none of them. Note that if you *know* this will *only* be used on ASP.NET Core, then [you don't need `ConfigureAwait(false)`](https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html). – Stephen Cleary Jan 19 '21 at 12:47

0 Answers0