![](/img/trans.png)
[英]C# HttpClient - PostAsync doesn't return (even with ConfigureAwait)
[英]HttpClient's PostAsync method blocks even though ConfigureAwait(false) is used
我花了很多時間試圖弄清楚這一點,但不幸的是沒有結果。 我將不勝感激。
問題是盡管我使用await
和ConfigureAwait(false)
,但PostAsync
調用阻止了事件。 在UI線程上調用以下處理程序:
private async void OnApplicationLaunching(object sender, LaunchingEventArgs e)
{
using (var httpClient = new HttpClient())
{
var content = new List<KeyValuePair<string, string>>();
var urlEncodedContent = new FormUrlEncodedContent(content);
await httpClient.PostAsync("url address", urlEncodedContent).ConfigureAwait(false);
}
}
編輯1
編輯2
這是另一個代碼示例,與以前的代碼示例沒有很大不同,但更像是Stephen博客中的代碼示例。
http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html中的 “防止死鎖”部分
http://blog.stephencleary.com/2012/02/async-and-await.html中的 “避免上下文”部分
private async void OnApplicationLaunching(object sender, LaunchingEventArgs e)
{
await this.SendSth();
// here I want to know for sure that data has already been sent
}
private async Task SendSth()
{
using (var httpClient = new HttpClient())
{
var content = new List<KeyValuePair<string, string>>();
var urlEncodedContent = new FormUrlEncodedContent(content);
await httpClient.PostAsync("some url", urlEncodedContent).ConfigureAwait(false);
}
}
順便說一句,感謝斯蒂芬的出色文章。 他們有很多幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.