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

Is IHubContext<THub> of SignalR thread-safe?

我在 ASP.NET MVC 核心控制器中执行此操作:

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

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

TimerManager class 看起来像这样:

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> 及其方法是线程安全的吗?

您可以安全地使用 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