我有一个公共的async
方法,它调用3个不同的API来获取一些数据,然后将响应发布到下一个API。现在基于Stephen cleary的文章here to avoid deadlock:
false 1.在你的“库”异步方法中,尽可能使用ConfigureAwait(
)。
2.不要阻塞任务;一直使用async。
我想知道私有异步方法是否也是如此?当我调用private
异步方法时也需要使用ConfigureAwait(false)
吗?所以这条线上的东西
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);
}
}
Update1
我也已经通过了所以post here,但回答建议使用自定义的NoSynchronizationContextScope。
我想知道我是否需要在私有方法上使用ConfigureAwait(false)?
发布于 2016-09-16 04:09:08
我想知道我是否需要在私有方法上使用ConfigureAwait(false)?
一般来说,是的。除非方法需要上下文,否则每个await
都应该使用ConfigureAwait(false)
。
但是,如果您使用NoSynchronizationContextScope
,那么就不需要ConfigureAwait(false)
了。
https://stackoverflow.com/questions/39518980
复制相似问题