【发布时间】:2014-03-28 20:30:30
【问题描述】:
我有以下代码连接到 SignalR 集线器
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 方法中,我有这个
StartListening();
但是,Resharper 提示我“考虑将 'await' 运算符应用于调用结果”
所以我这样做了:
Log.Info("Connecting to SignalR hub...");
StartListening().Wait();
Log.Info("Connected!");
但是,这会导致我的 UI 线程挂起,并且永远不会将 Connected! 打印到日志文件中。
所以我的问题是,我应该什么时候使用Wait()?什么情况下应该使用Wait(),什么时候不应该使用Wait()?
【问题讨论】:
-
所以,它说“考虑应用 await”,然后你做了一些不同的事情 - 为什么你决定不听从建议并实际使用
await? -
啊啊啊是的!我忽略了这一点。我以为他们是一样的。感谢您指出这一点!
标签: c# .net task-parallel-library signalr async-await