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?
You can use IHubContext<THub>
safely with Timer
.
IHubContext<THub>
is a singleton:
services.TryAddSingleton(typeof(IHubContext<>), typeof(HubContext<>));