简体   繁体   中英

Application hangs when using a second hub from within the first hub

In my application I have 2 hubs (and use 2 separate connections). One hub and its connection is created from within a class. The other one from within a form.

In the first proxy I do:

var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext()

workProxy.On("DoWork", () =>
{
    Task.Factory.StartNew(() =>
    {
        OnDoWork?.Invoke(this, new EventArgs());
    },
    CancellationToken.None, TaskCreationOptions.None, uiTaskScheduler);
});

I'm doing the above because I'm opening a form within On and if I don't do the above, I get a cross-thread exception.

A second form subscribes to the OnDoWork event which in turn opens the actual form which has the hub connection and proxy.

On the form's OnShown event I do:

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();
}

The form can be opened directly without being called from the first proxy. In this situation, everything works fine. However, when I open the form from within the first proxy, the application hangs on this line:

hubConnection.Start().Wait();

Is the problem because I'm starting a second connection within a form which is opened within a task? Is there a solution to this problem?

.Wait() is blocking calling that can cause dealocks. You should be awaiting the Task returned from Start() , ex await hubConnection.Start() , to do this you'll need to make the OnShown event async.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM