Search code examples
c#asp.net-coreasp.net-core-hosted-services

IHostedService in C# doesn't trigger method every time?


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

Solution

  • The following line:

    var _timer = new System.Threading.Timer(LoadData, null, TimeSpan.Zero, TimeSpan.FromMinutes(2));
    

    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:

    System.Threading.Timer _timer;
    
    public Task StartAsync(CancellationToken stoppingToken)
    {
        _timer = new System.Threading.Timer(LoadData, null, TimeSpan.Zero, TimeSpan.FromMinutes(2));
    
        return Task.CompletedTask;
    }
    

    Also switching to System.Timers.Timer could also work (but have not tested it).

    See also: