Search code examples
c#asp.net-corethread-safetysignalrasp.net-core-signalr

Is IHubContext<THub> of SignalR thread-safe?


I have this action inside an ASP.NET MVC Core controller:

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

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

The TimerManager class looks like this:

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

But I don't know if calling _hub.Clients.All.SendAsync() will have concurrency problems. Is IHubContext<THub> and its methods thread-safe?


Solution

  • You can use IHubContext<THub> safely with Timer.

    IHubContext<THub> is a singleton:

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

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