接上一篇,在上一篇里面有个缺陷,等所有SignalR连接都关闭,后台线程才全部终止,这一篇修改一下,每个连接维护他自己的线程,关闭连接就关闭属于他自己的的那个线程,下面使用一个字典来保存连接和线程之间的关系
using HenryMes.BLL;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading;
using System.Threading.Tasks;
using HenryMes.Model;
using System.Collections.Generic;
using System;
namespace HenryMes.WebProtal.SignalR.HomePage
{
[HubName("OrderProductStatusHub")]
public class OrderProductStatusHub : Hub
{
private static Dictionary<string, CancellationTokenSource> _connections = new Dictionary<string, CancellationTokenSource>();
public void Send(string connectId)
{
if (!_connections.ContainsKey(connectId))
{
var tokenSource = new CancellationTokenSource();
_connections.Add(connectId, tokenSource);
var orderProduction = new OrdersProductionBll();
Task.Run(() =>
{
while (!tokenSource.Token.IsCancellationRequested)
{
var model = new List<OrderProductStatusModel>();
model = orderProduction.OrderProductStatus();
OrderProductStatusNotifier.RefreshOrderProductStatus(connectId, model);
//2秒推送一次
Thread.Sleep(2000);
}
}, tokenSource.Token);
}
}
public override Task OnDisconnected(bool stopCalled)
{
if (_connections.ContainsKey(Context.ConnectionId))
{
try
{
var _tokenSource = _connections[Context.ConnectionId];
_tokenSource.Cancel();
_connections.Remove(Context.ConnectionId);
}
catch (Exception ex)
{
throw ex;
}
}
return base.OnDisconnected(stopCalled);
}
}
}