C#HttpClient.PostAsync并等待崩溃的应用程序 [英] C# HttpClient.PostAsync and await crashing app

查看:624
本文介绍了C#HttpClient.PostAsync并等待崩溃的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#相当陌生.我正在使用await关键字来调用HttpClient的API.

I am quite new to C#. I'm using the await keyword to invoke HttpClient's 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.
}

我有2个似乎无法解决的问题

I have 2 problems which I can't seem to be able to solve

  1. client.PostAsync()方法运行后,我的应用程序崩溃了.就那么简单.我知道这是因为主线程没有其他要处理的东西,但是上面的所有代码都在 MainWindow 的构造函数代码中发生,因此在 await之后还有很多事情要做
  2. 永远不会触发异常.如何确保在 client.PostAsync()中调用我的异常catch子句会引发异常.
  1. After the client.PostAsync() method runs, my app just crashes. Simple as that. I understand it's because the main thread doesn't have anything else to process, but all the code above happens in the constructor code of MainWindow, so there is a lot more to do after the await
  2. The exception is never triggered. How do I ensure that my exception catch clause is invoked in client.PostAsync() throws an exception.

任何可行的代码建议都可以:).

Any code suggestion that just works would do :).

推荐答案

您正在将阻塞调用( .Result .Wait())与异步调用混合在一起,导致僵局.

You are mixing blocking calls (.Result, .Wait()) with async calls which can lead to deadlocks.

使 initSocketTo 异步.

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

也不要尝试在构造函数中进行异步处理.在生命周期的后期移动较重的过程.您甚至可以引发一个事件并在另一个线程上处理该事件,以免阻塞流程.

Also do not try to do async in the constructor. Move the heavier processes later in the life cycle. You could even raise an event and handle that on another thread so as not to block the flow.

这篇关于C#HttpClient.PostAsync并等待崩溃的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆