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

问题描述 投票:0回答:2

我对 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
  2. 之后还有很多事情要做
  3. 永远不会触发异常。如何确保在
    client.PostAsync()
    抛出异常时调用我的异常 catch 子句。

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

c# .net wpf http dotnet-httpclient
2个回答
2
投票

您将阻塞调用(

.Result
.Wait()
)与异步调用混合在一起,这可能会导致死锁。

使

initSocketTo
异步。

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

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


0
投票

当我创建控制台应用程序时,这发生在我身上。

我通过将主程序设置为

解决了这个问题
static async Task Main(string[] args)

然后等待你的主程序中的任何工作。

© www.soinside.com 2019 - 2024. All rights reserved.