This is my code in .net core 5 which wants to trigger a function every 2 minutes. I don't know why LoadData function doesn't get triggered after 2 minutes and only get triggered the first time?
public Task StartAsync(CancellationToken stoppingToken)
{
var _timer = new System.Threading.Timer(LoadData, null, TimeSpan.Zero, TimeSpan.FromMinutes(2));
return Task.CompletedTask;
}
private async void LoadData(object state)
{
var res = await _repository.GetAsync();
//....
}
The following line:
Will create a timer and save the reference only to local variable, allowing the GC to collect the
System.Threading.Timer. Workaround can be to introduce a field:Also switching to
System.Timers.Timercould also work (but have not tested it).See also: