我有一个公共async方法,它调用3个不同的API来获取一些数据,然后将响应发布到下一个API.现在,根据斯蒂芬·克利里的文章,在这里,以避免死锁:
1.在"库"异步方法中,尽可能使用ConfigureAwait(false).
2.不要阻止任务; 一直使用async.
我想知道私有异步方法是否也是如此?ConfigureAwait(false)我在调用private异步方法时是否需要使用?所以沿途就行了
public async Task<int> ProcessAsync(ServiceTaskArgument arg)
{
// do i need to use ConfigureAwait here while calling private async method?
var response1 = await GetAPI1().ConfigureAwait(false);
// do i need to use ConfigureAwait here while calling private async method?
var response2= await PostAPI2(response1).ConfigureAwait(false);
// do i need to use ConfigureAwait here while calling private async method?
await PostAPI3(response2).ConfigureAwait(false);
return 1;
}
private async Task<string> GetAPI1()
{
var httpResponse = await _httpClient.GetAsync("api1").ConfigureAwait(false);
// do i need to use ConfigureAwait here while calling private async method?
await EnsureHttpResponseIsOk(httpResponse).ConfigureAwait(false);
return await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
private async Task<string> PostAPI2(string data)
{
var stringContent = new StringContent(data, Encoding.UTF8, "application/json");
var httpResponse = await _httpClient.PostAsync("api2", stringContent).ConfigureAwait(false);
// do i need to use ConfigureAwait here while calling private async method?
await EnsureHttpResponseIsOk(httpResponse).ConfigureAwait(false);
return await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
private async Task<string> PostAPI3(string data)
{
var stringContent = new StringContent(data, Encoding.UTF8, "application/json");
var httpResponse = await _httpClient.PostAsync("api3", stringContent).ConfigureAwait(false);
// do i need to use ConfigureAwait here while calling private async method?
await EnsureHttpResponseIsOk(httpResponse).ConfigureAwait(false);
return await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
private async Task EnsureHttpResponseIsOk(HttpResponseMessage httpResponse)
{
if (!httpResponse.IsSuccessStatusCode)
{
var content = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new MyHttpClientException("Unexpected error has occurred while invoking http client.", content, httpResponse.Headers);
}
}
Run Code Online (Sandbox Code Playgroud)
Update1
此外,我在这里发布了SO帖子,但回答建议使用自定义 NoSynchronizationContextScope.
我想知道我是否需要在私有方法上使用ConfigureAwait(false)?
我想知道我是否需要在私有方法上使用ConfigureAwait(false)?
作为一般规则,是的.除非方法需要其上下文,否则ConfigureAwait(false)应该用于每一个 .await
但是,如果您使用NoSynchronizationContextScope,则无需使用ConfigureAwait(false).