C#HttpClient.PostAsync并等待崩溃的应用程序

时间:2017-09-09 17:04:34

标签: c# .net wpf http dotnet-httpclient

我对C#很新。我正在使用await关键字来调用HttpClient的API。

static async Task<HttpResponseMessage> CreateChannel(string channelName)
{
    try
    {
        HttpClient client = new HttpClient();
        var req = new 
        {
            id= channelName
        };
        StringContent content = new StringContent(JsonConvert.SerializeObject(req).ToString(), Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("http://localhost:3000/channel", content);
        response.EnsureSuccessStatusCode();
        return response;
    }
    catch (Exception ex)
    {
       ...
        var view = new Dialog();
       ...
        var result = await DialogHost.Show(view);
        return null;
    }
}

private void initSocketIo(string channel)
{
    CreateChannel(channel).Wait();
    ...
    // after this method we init UI etc.
}

我有两个问题似乎无法解决

  1. client.PostAsync()方法运行后,我的应用程序崩溃了。就那么简单。我理解这是因为主线程没有其他任何东西需要处理,但上面的所有代码都发生在MainWindow的构造函数代码中,所以在await之后还有很多工作要做LI>
  2. 永远不会触发异常。如何确保在client.PostAsync()中调用异常catch子句会引发异常。
  3. 任何正常工作的代码建议都可以:)。

1 个答案:

答案 0 :(得分:0)

您正在将阻止调用(.Result.Wait())与异步调用混合在一起,这会导致死锁。

initSocketTo异步。

private async Task initSocketIo(string channel) {
    var response = await CreateChannel(channel);
    ...
    // after this method we init UI etc.
}

也不要尝试在构造函数中执行异步。在生命周期的后期移动较重的进程。你甚至可以举起一个事件并在另一个线程上处理它,以免阻塞流程。