If HttpMessageHandler uses ConfigureAwait (false)

If I have an asynchronous call inside the HttpMessageHandler, should it use the .ConfigureAwait method for example.

/// <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;
    }
}

      

+3


source to share


2 answers


I assume that you are talking about this line, and if it is ok, ConfigureAwait(false)

on this line.

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

      



No, on the next line, you are calling SendAsync

with an Http request. You cannot switch threads and still have access to the correct HTTP request context, so you need to use ConfigureAwait(true)

or not include the call at all ConfigureAwait

.

+3


source


You should always use ConfigureAwait(false)

when code after expected code should not revert to the context provided by the sync 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);
    }
}

      

+3


source







All Articles