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.

2
  • 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? Commented Jan 18, 2021 at 23:57
  • 2
    "when it is already called on a different synchronization context than original" - async has a "fast path" 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). Commented Jan 19, 2021 at 12:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.