0

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

4

1 回答 1

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

于 2019-11-24T11:04:32.873 回答