Wait()导致UI线程挂起-什么时候应使用Wait()? [英] Wait() causes UI thread to hang - when should Wait() be used?
问题描述
我有以下代码连接到SignalR集线器
I have the following code that connects to a SignalR Hub
private static async Task StartListening()
{
try
{
var hubConnection = new HubConnection("http://localhost:8080/");
IHubProxy hubProxy = hubConnection.CreateHubProxy("Broadcaster");
hubProxy.On<EventData>("notifyCardAccessEvent", eventData =>
{
Log.Info(string.Format("Incoming data: {0} {1}", eventData.Id, eventData.DateTime));
});
ServicePointManager.DefaultConnectionLimit = 10;
await hubConnection.Start();
Log.Info("Connected");
}
catch (Exception ex)
{
Log.Error(ex);
}
}
在我的Form_Load
方法中,我有这个
In my Form_Load
method, I have this
StartListening();
但是,Resharper提示我考虑将'await'运算符应用于呼叫结果"
However, Resharper prompts me to "consider applying the 'await' operator to the result of the call"
所以我做到了:
Log.Info("Connecting to SignalR hub...");
StartListening().Wait();
Log.Info("Connected!");
但是,这导致我的UI线程挂起,并且Connected!
从未打印到日志文件中.
However, this causes my UI thread to hang and Connected!
is never printed to the log file.
所以我的问题是,什么时候应该使用Wait()
?我应该使用Wait()的实例和场景是什么,什么时候不应该使用Wait()
?
So my question is, when should I use Wait()
? What are the instances and scenarios that I should use Wait(), and when should I not use Wait()
?
推荐答案
await
不是Wait
.目前尚不清楚调用StartListening()
的代码是什么,但建议使用await
来替代它,
await
is not Wait
. It is unclear what the code is that is calling StartListening()
, but one option is to await
it, as suggested:
await StartListening();
但是,在其他一些情况下,最好什么也不做:
However, in some other cases it may be better to do nothing at all:
StartListening(); // drop the Task on the floor
,或者使用ContinueWith
进行手动继续.由于StartListening
方法会捕获任何异常,因此仅忽略返回的Task
并没有什么不妥-因此,您已经拥有了什么.我建议将其命名为StartListeningAsync
.
or perhaps use ContinueWith
for a manual continuation. Since the StartListening
method catches any exceptions, there isn't anything wrong with just ignoring the returned Task
- so what you had already. I would suggest calling it StartListeningAsync
, though.
发生死锁的原因是,如果使用Wait
,则UI线程将阻止等待异步方法完成,但是该异步方法正在捕获同步上下文,这意味着为了处理它尝试的每个连续性进入UI线程-已被阻止...在其上 .
The reason for the deadlock is that if you use Wait
, your UI thread blocks waiting on an asynchronous method to complete, but that asynchronous method is capturing the sync-context, which means in order to process each continuation it tries to get onto the UI thread - which is blocked... on it.
这篇关于Wait()导致UI线程挂起-什么时候应使用Wait()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!