Reputation: 646
I am using latest SignalR (v:1.1.1), and trying to simple call the Hub method periodically, every 3 seconds. I have seen many questions here and have duplicated the way, but GetHubContext
method doesn't seem to be returning the correct instance of the class, so I can't call the methods of that class. You can duplicate the case with the following steps:
MyHub.cs:
public class MyHub : Hub
{
public void SendMessage(string message)
{
Clients.All.triggerMessage(message);
}
}
Global.asax:
Task.Factory.StartNew(() =>
{
while (true)
{
var myHub = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
myHub.Clients.All.SendMessage("Hello World");
System.Threading.Thread.Sleep(3000);
}
})
.ContinueWith(t => { throw new Exception("The task threw an exception", t.Exception); }, TaskContinuationOptions.OnlyOnFaulted);
I think this is as simple as it gets. I think this is correct way of doing it, but the debugger never hits SendMessage
method. Does anyone know am I missing something very obvious? I am just trying to schedule a call to the SignalR client from the server for every 3 seconds.
Upvotes: 1
Views: 375
Reputation: 646
I ended changing the way the hub was created:
MyHostHub.cs
private readonly MyHost _host;
public MyHostHub(){ _host = new MyHost(); }
MyHost:
private readonly static Lazy<IHubConnectionContext> _clients = new Lazy<IHubConnectionContext>(() => GlobalHost.ConnectionManager.GetHubContext<MyHostHub>().Clients);
private IHubConnectionContext Clients
{
get { return _clients.Value; }
}
public void SendMessage(string message)
{
Clients.All.triggerMessage(message);
}
My Global.asax:
Task.Factory.StartNew(() =>
{
while (true)
{
var myHost = ObjectFactory.GetInstance<MyHost>();
myHost.SendMessage();
Thread.Sleep(3000);
}
})
.ContinueWith(t => { throw new Exception("The task threw an exception", t.Exception); }, TaskContinuationOptions.OnlyOnFaulted);
This seems to be working just fine. Basically I moved out the code from the Hub
class to another class that I can call in Global.asax but my hub has a reference for host.
Upvotes: 1
Reputation: 1553
On your Global.asax file, when you call 'myHub.Clients.All.SendMessage("Hello World")' it sends a message to the client, it does not call the SendMessage method in your class MyHub.
Please read SignalR Documentation to see some samples
Upvotes: 1