我有一个自托管信号器集线器,配置如下:
using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
using Microsoft.Owin.Cors;
namespace SignalRSelfHost
{
class Program
{
static void Main(string[] args)
{
// This will *ONLY* bind to localhost, if you want to bind to all addresses
// use http://*:8080 to bind to all addresses.
// See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
// for more information.
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{
ConcurrentDictionary<string, string[]> userList = new ConcurrentDictionary<string, string[]>();
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
我有一些将要运行的过程&#34;永远&#34;
CancellationTokenSource cts = new CancellationTokenSource();
var token = cts.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
//update the userList wich should be shared with hub, and call some signalr notification on hub clients
Thread.Sleep(1000);
}
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
我试图将此进程放在集线器构造函数中,但它没有运行。
那么,如何实现这个目标?
答案 0 :(得分:0)
Hub仅在SignalR请求期间存在,因此您不应在Hub中将此类代码移至后台工作程序并使用
调用集线器GlobalHost.ConnectionManager.GetHubContext<MyHub>().Clients.All.addMessage(name, message);