我有公開async
方法,它調用3個不同的API來獲取一些數據,然後將響應發佈到下一個API。現在基於Stephen Cleary的文章here來避免死鎖:對私有異步方法使用ConfigureAwait(false)?
1.在您的「庫」異步方法中,儘可能使用ConfigureAwait(false)。
2.不要阻止任務;一直使用異步。
我想知道私人異步方法是否也是如此?當我打電話給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
此外,我所經歷的東西SO發佈here,但回答提示使用自定義NoSynchronizationContextScope。
我想知道是否需要在私有方法上使用ConfigureAwait(false)?
參考實現:http://stackoverflow.com/questions/28305968/use-task-run-in-synchronous-method-to-avoid-deadlock-waiting-on-async-method – Caramiriel