如果我在HttpMessageHandler中有异步调用,它应该使用.ConfigureAwait方法,例如
/// <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;
}
}
答案 0 :(得分:3)
当等待代码之后的代码不需要返回到同步上下文提供的上下文时,您应该始终使用ConfigureAwait(false)
。
/// <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);
}
}
答案 1 :(得分:2)
我假设您正在谈论这一行,如果可以在该行上ConfigureAwait(false)
。
await request.Content.AssignMd5Hash().ConfigureAwait(false);
不,在下一行,您使用Http请求调用SendAsync
。您无法切换线程,仍然可以访问正确的http请求上下文,因此您必须使用ConfigureAwait(true)
或忽略对ConfigureAwait
的所有呼叫。