3

If I have an asynchronous call inside a HttpMessageHandler, should it use the .ConfigureAwait method e.g.

/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content == null)
        {
            return await base.SendAsync(request, cancellationToken);
        }

        await request.Content.AssignMd5Hash().ConfigureAwait(false);

        var response = await base.SendAsync(request, cancellationToken);

        return response;
    }
}

2 Answers 2

4

You should always use ConfigureAwait(false) when the code after the awaited code doesn't need to get back to the context provided by the synchronization context.

/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            await request.Content.AssignMd5Hash().ConfigureAwait(false);
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I assume you are talking about this line and if it is OK to have ConfigureAwait(false) on that line.

await request.Content.AssignMd5Hash().ConfigureAwait(false);

No, on the next line you call SendAsync with the Http Request. You can't switch threads and still have access to the correct http request context so you have to use ConfigureAwait(true) or omit the call to ConfigureAwait all together.

2 Comments

thanks rationale for the question was all the other topics around server-side code should always use ConfigureAwait(false) - I'll use ConfigureAwait(true) so we don't confuse it
How come? The correct HTTP request is being passed as an argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.