【发布时间】:2016-09-15 19:33:09
【问题描述】:
我有 public async 方法,它调用 3 个不同的 API 来获取一些数据,然后将响应发布到下一个 API。现在根据 Stephen cleary 的文章here 来避免死锁:
1.在您的“库”异步方法中,尽可能使用 ConfigureAwait(false)。
2.不要阻塞任务;一直使用异步。
我想知道私有异步方法是否也是如此?当我调用private async 方法时,是否还需要使用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);
}
}
更新1
我也经历过 SO 帖子 here,但回答建议使用自定义 NoSynchronizationContextScope。
我想知道是否需要在私有方法上使用 ConfigureAwait(false)?
【问题讨论】:
标签: c# async-await