我对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.
}
我有两个问题似乎无法解决
MainWindow
的构造函数代码中,所以在await
之后还有很多工作要做LI>
client.PostAsync()
中调用异常catch子句会引发异常。任何正常工作的代码建议都可以:)。
答案 0 :(得分:0)
您正在将阻止调用(.Result
,.Wait()
)与异步调用混合在一起,这会导致死锁。
让initSocketTo
异步。
private async Task initSocketIo(string channel) {
var response = await CreateChannel(channel);
...
// after this method we init UI etc.
}
也不要尝试在构造函数中执行异步。在生命周期的后期移动较重的进程。你甚至可以举起一个事件并在另一个线程上处理它,以免阻塞流程。