我在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>
及其方法是线程安全的吗?
答案 0 :(得分:1)
您可以将IHubContext<THub>
与Timer
安全地使用。
IHubContext<THub>
是单例:
services.TryAddSingleton(typeof(IHubContext<>), typeof(HubContext<>));