从第一个集线器中使用第二个集线器时应用程序挂起
Application hangs when using a second hub from within the first hub
在我的应用程序中,我有 2 个集线器(并使用 2 个单独的连接)。一个集线器及其连接是在 class 中创建的。另一个来自表格。
我做的第一个代理:
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext()
workProxy.On("DoWork", () =>
{
Task.Factory.StartNew(() =>
{
OnDoWork?.Invoke(this, new EventArgs());
},
CancellationToken.None, TaskCreationOptions.None, uiTaskScheduler);
});
我这样做是因为我在 On
中打开一个表单,如果我不这样做,我会得到一个跨线程异常。
第二个表单订阅 OnDoWork 事件,该事件反过来打开具有集线器连接和代理的实际表单。
在表单的 OnShown
事件中我做了:
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
hubConnection = new HubConnection("myhubsurl");
hubProxy = hubConnection.CreateHubProxy("SecondHub");
doWork = hubProxy.On<IEnumerable<Item>>("DoWork", items => WorkOnItems(items));
hubConnection.Start().Wait();
}
表单可以直接打开,无需从第一个代理调用。在这种情况下,一切正常。但是,当我从第一个代理中打开表单时,应用程序挂在这一行:
hubConnection.Start().Wait();
问题是因为我在任务中打开的表单中开始第二个连接吗?这个问题有解决办法吗?
.Wait()
正在阻止可能导致取消锁定的调用。您应该等待从 Start()
、e.x 返回的 Task
。 await hubConnection.Start()
,为此您需要使 OnShown
事件异步。
protected async override void OnShown(EventArgs e)
{
base.OnShown(e);
hubConnection = new HubConnection("myhubsurl");
hubProxy = hubConnection.CreateHubProxy("SecondHub");
doWork = hubProxy.On<IEnumerable<Item>>("DoWork", items => WorkOnItems(items));
await hubConnection.Start();
}
在我的应用程序中,我有 2 个集线器(并使用 2 个单独的连接)。一个集线器及其连接是在 class 中创建的。另一个来自表格。
我做的第一个代理:
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext()
workProxy.On("DoWork", () =>
{
Task.Factory.StartNew(() =>
{
OnDoWork?.Invoke(this, new EventArgs());
},
CancellationToken.None, TaskCreationOptions.None, uiTaskScheduler);
});
我这样做是因为我在 On
中打开一个表单,如果我不这样做,我会得到一个跨线程异常。
第二个表单订阅 OnDoWork 事件,该事件反过来打开具有集线器连接和代理的实际表单。
在表单的 OnShown
事件中我做了:
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
hubConnection = new HubConnection("myhubsurl");
hubProxy = hubConnection.CreateHubProxy("SecondHub");
doWork = hubProxy.On<IEnumerable<Item>>("DoWork", items => WorkOnItems(items));
hubConnection.Start().Wait();
}
表单可以直接打开,无需从第一个代理调用。在这种情况下,一切正常。但是,当我从第一个代理中打开表单时,应用程序挂在这一行:
hubConnection.Start().Wait();
问题是因为我在任务中打开的表单中开始第二个连接吗?这个问题有解决办法吗?
.Wait()
正在阻止可能导致取消锁定的调用。您应该等待从 Start()
、e.x 返回的 Task
。 await hubConnection.Start()
,为此您需要使 OnShown
事件异步。
protected async override void OnShown(EventArgs e)
{
base.OnShown(e);
hubConnection = new HubConnection("myhubsurl");
hubProxy = hubConnection.CreateHubProxy("SecondHub");
doWork = hubProxy.On<IEnumerable<Item>>("DoWork", items => WorkOnItems(items));
await hubConnection.Start();
}