Alessandro
Alessandro

Reputation: 61

SignalR .NET client: subsequent method Invoke with same connection opened

I have a .NET client app, connected to a SignalR Hub hosted with a .net mvc5 webapp. The main routine of the client app does:

int num1 = _myService.GetSomeHubMethod();
int num2 = _myService.GetSomeOtherHubMethod();
...

where _myService is an instance of the class:

public class MyService
{
    ...
    private HubConnection connection;
    private IHubProxy hubProxy;
    ...

    public MyService()
    {
         ...
         if (BASE_SITE_URL == null)
            BASE_SITE_URL = ConfigurationManager.AppSettings["BASE_SITE_URL"].ToString();
        if (connection == null)
            connection = new HubConnection(BASE_SITE_URL);
        if (hubProxy == null)
            hubProxy = connection.CreateHubProxy("MyHub");

        connection.Start().Wait();
    }

    ...

    public int GetSomeHubMethod()
    {
        //connection.Start().Wait();

        var t = hubProxy.Invoke<int>("SomeHubMethod");

        int result = t.Result;

        //connection.Stop();

        return result;
    }

    public int GetSomeOtherHubMethod()
    {
        //connection.Start().Wait();

        var t = hubProxy.Invoke<int>("SomeOtherHubMethod");

        int result = t.Result;

        //connection.Stop();

        return result;
    }

}

and the two hub methods, in the SignalR hub (server side) are:

public class MyHub : Hub
{
    ...
    public int SomeHubMethod()
    { return 1; }

    public int SomeOtherHubMethod()
    { return 2; }        

}

The problem is: the first call is correctly evaluated, but the second call "hangs" in the int result = t.Result; line. In particular, t.Status is "WaitingForActivation".

If I switch the order of the two calls in the main routine, the first is executed and the seconds "hangs".

Note: if I start and stop the connection inside the two methods (see commented lines) instead of calling connection.Start().Wait() in the constructor of MyService, it works perfectly, but it needs too much time to stop and start.

Thanks everybody for help!

Upvotes: 1

Views: 1620

Answers (1)

Alessandro
Alessandro

Reputation: 61

Ok, it seems it's a deadlock. I had to modify methods this way:

public async Task<int> SomeHubMethod()
{
    return await Task.FromResult<int>(1);
}

...

public async Task<int> GetSomeHubMethod()
{
    return await chatHubProxy.Invoke<int>("SomeHubMethod");
}

...

int num1 = await _myService.GetSomeHubMethod();

Ok, I confess I still have much work to do with async stuff...

Upvotes: 1

Related Questions