即使使用了ConfigureAwait(false),HttpClient的PostAsync方法也会阻塞

时间:2016-05-27 12:08:34

标签: c# async-await deadlock dotnet-httpclient

我花了很多时间试图解决这个问题,但遗憾的是无济于事。我很感激任何帮助。

问题在于PostAsync调用会阻止事件,尽管我使用awaitConfigureAwait(false)。在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

  • 我使用WindowsPhone 8.0 silverlight
  • 在我看来,这是一个僵局。执行被阻止,直到出现异常&#34;任务被取消&#34;消息
  • 我对&#34;火和忘记&#34;不感兴趣。我需要确保在允许进一步执行之前发送数据。

修改2

这是另一个代码示例,它与前一个代码示例没有什么不同,但是beter类似于Stephen博客的代码示例

部分&#34;防止僵局&#34;在http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

部分&#34;避免语境&#34;在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);
    }
}

顺便说一下,感谢斯蒂芬的精彩文章。他们帮助很多。

1 个答案:

答案 0 :(得分:-1)

根据我对C#中异步编程的理解,应该在库中调用ConfigureAwait

请参阅Stephen Cleary的article。同时检查this

相关问题