Invoke signalR method inside the client method

16.8k Views Asked by At

I am using signalR version 2.1.2. And I am using console application as a SignalrClient. I invoke a method-A and after getting response , I have to invoke method-B based on the response from method-A. In this scenario I am able to successfully invoke and not getting any response from method-B. Whats my mistake??. Here my code

var hubConnection = new HubConnection("Url");

IHubProxy proxy = hubConnection.CreateHubProxy("HitProxy");
proxy.On<bool>("Client-method-B", (retvAl) =>
{
    Console.WriteLine("Method-B response");
});

proxy.On<bool>("Client-method-A", (isConnected) =>
{
    Console.WriteLine("Method-A response");
    if(isConnected)
    {
        proxy.Invoke("method-B", "someValue").Wait();
    }
});

hubConnection.Start().Wait();
proxy.Invoke("method-A", "123").Wait();

Here I am not getting any response from 'method-B'. Thanks.

2

There are 2 best solutions below

1
Xmindz On BEST ANSWER

The best way to get the result from the SignalR server method is to read its return value instead of invoking a client method at the caller side. For example, you may read the response from the method-A as follows:

proxy.Invoke("method-A", "123").ContinueWith((t) =>
{
  bool isConnected = t.Result;
});

Expecting the signature of method-A is something like:

public bool method-A(string p);

This way you don't have to invoke a client method just to return the result of a server method to the caller. You may invoke another server method from the callback of another server method call like this:

proxy.Invoke("method-A", "123").ContinueWith((t) =>
{
  bool isConnected = t.Result;
  if(isConnected)
  {
    proxy.Invoke("method-B", "someValue").ContinueWith((u) =>
    {
      Console.WriteLine("Method-B response: " + u.Result);
    });
  }
});

Assumes that method-B returns a string value at the server side.

4
Łukasz Zwierko On

In the code supplied you create the proxy

IHubProxy proxy = hubConnection.CreateHubProxy("HitProxy");

but later u use

hubProxy.Invoke("method-B", "someValue").Wait();

so is it just a type and proxy == hubProxy ?

I would advice yout to do 3 things

  1. use wireshark to check if there is any actual traffic to server when invoking method B
  2. check the server side if the server properly invokes the operation
  3. you might want to try to dispatch operation B so it's not invoke in the callback context - depending on your app you might want to use Dispatcher or just Task.Run. I'm not sure about signalr client but some frameworks don't like when you invoke their methods in callbacks.