SignalR的IHubContext <THub>是线程安全的吗?

时间:2019-11-20 20:39:35

标签: c# asp.net-core thread-safety signalr asp.net-core-signalr

我在ASP.NET MVC Core控制器中执行以下操作:

public IActionResult Get()
{
    var timeManager = new TimerManager(() =>
    {
        _hub.Clients.All.SendAsync("transferchartdata", DataManager.GetData());
    });

    return Ok(new { Message = "Request completed" });
}

TimerManager类如下所示:

public class TimerManager
{
    private Timer _timer;
    private AutoResetEvent _autoResetEvent;
    private Action _action;

    public DateTime TimerStarted { get; }

    public TimerManager(Action action)
    {
        _action = action;
        _autoResetEvent = new AutoResetEvent(false);
        _timer = new Timer(Execute, _autoResetEvent, 1000, 2000);
        TimerStarted = DateTime.Now;
    }

    public void Execute(object stateInfo)
    {
        _action();

        if ((DateTime.Now - TimerStarted).Seconds > 60)
        {
            _timer.Dispose();
        }
    }
}

但是我不知道调用_hub.Clients.All.SendAsync()是否会有并发问题。 IHubContext<THub>及其方法是线程安全的吗?

1 个答案:

答案 0 :(得分:1)

您可以将IHubContext<THub>Timer安全地使用。

IHubContext<THub>是单例:

  
services.TryAddSingleton(typeof(IHubContext<>), typeof(HubContext<>));

参考:https://github.com/aspnet/AspNetCore/blob/c84e37f30def9ff0b2d12e877e3de6c283be6145/src/SignalR/server/Core/src/SignalRDependencyInjectionExtensions.cs#L26