【问题标题】:How to use signalr with some parallel (background) processes?如何将信号器与一些并行(后台)进程一起使用?
【发布时间】:2014-08-29 11:19:35
【问题描述】:

我有一个自托管信号器集线器,配置如下:

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

我有一些进程将“永远”运行

CancellationTokenSource cts = new CancellationTokenSource();
var token = cts.Token;

Task.Factory.StartNew(() =>
{
    while (true)
    {
        //update the userList which should be shared with hub, and call some signalr notification on hub clients
        Thread.Sleep(1000);
    }
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

我试图把这个过程放在 hub 构造函数中,但是效果不好。

那么,如何实现呢?

【问题讨论】:

  • 如果轮询真的是解决方案,我会质疑自己。在大多数情况下,您想要的是服务总线/事件聚合器等
  • 我有这台服务器,通过套接字我可以请求用户列表。

标签: c# parallel-processing signalr signalr-hub self-hosting


【解决方案1】:

集线器仅在 SignalR 请求期间存在,因此您不应让集线器中的此类代码将其移动到后台工作人员并使用调用集线器

GlobalHost.ConnectionManager.GetHubContext<MyHub>().Clients.All.addMessage(name, message);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多