0

I have tried to follow this tutorial on how to create a backgroundworker.

Most of the stuff wasn't useful for me, so I didn't include that. I have no need for a queue. I just need to have this backgroundworker running in the background doing stuff every X hours My worker looks like this. Unfortunately it seems like it never calls the ExecuteAsync method

public class EnergySolutionBackgroundWorker : BackgroundService
{       
    private readonly ILogger<EnergySolutionBackgroundWorker> _logger;

    public EnergySolutionBackgroundWorker(ILogger<EnergySolutionBackgroundWorker> logger)
    {         
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("{Type} is now running in the background.", nameof(BackgroundWorker));

        await BackgroundProcessing(stoppingToken);
    }

    public override Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogCritical("The {Type} is stopping due to a host shutdown.", nameof(BackgroundWorker));

        return base.StopAsync(cancellationToken);
    }

    private async Task BackgroundProcessing(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await Task.Delay(new TimeSpan(0, 0, 1), stoppingToken);

                // Doing some tasks
            }
            catch (Exception ex)
            {
                _logger.LogCritical("An error occurred when publishing a book. Exception: {@Exception}", ex);
            }
        }
    }        
}

In Startup.cs I have the following:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddHostedService<EnergySolutionBackgroundWorker>();
    }

From my understanding, this should be enough for it to automatically start the backgroundworker during startup, but that is not the case. What am I doing wrong?

3
  • "it seems like it never calls the ExecuteAsync method" Is this message logged "{Type} is now running in the background."?
    – abdusco
    Aug 13, 2021 at 9:48
  • 1
    I just tried your code and it works perfectly. Probably something is wrong with // Doing some tasks
    – mtkachenko
    Aug 13, 2021 at 10:08
  • I can't see the message logged anywhere. Wouldn't that be in the output window? I also tried to add some code in the ExecuteAsync method where it should write to a simple txt file in C:\Temp, but it didn't do that either
    – Adagio
    Aug 13, 2021 at 10:59

2 Answers 2

0
  1. you can add timer in start function. A timed background task makes use of the System.Threading.Timer class. The timer triggers the task's DoWork method. The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:
internal class TimedHostedService : IHostedService, IDisposable
{
    private readonly ILogger _logger;
    private Timer _timer;

    public TimedHostedService(ILogger<TimedHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is starting.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, 
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation("Timed Background Service is working.");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}
  1. there is a reference
2
  • Timer doesn't work async, though. It doesn't release the thread to threadpool while waiting.
    – abdusco
    Aug 13, 2021 at 10:06
  • @abdusco a timer is async. In fact, Task.Delay uses a timer internally to signal a TaskCompletionSource. The callback can be an async void Aug 13, 2021 at 12:12
0

I believe I found the answer! Startup.cs is not run before the first call to the API is made. After calling a simple Test method in one of my controllers, the BackgroundProcessing method was called That's a bit annoying, as I was hoping I later could create a backgroundworker that loads a lot of data into memory instead of it happening when the first call is made

5
  • That's a bug in your code then. Startup.cs is used to configure the API. By definition, that happens before the API can receive even a single request. A BackgroundService is a singleton, so it does start before any requests. That doesn't mean it blocks requests until it finishes. If your BackgroundService startup code is too slow, it may not have finished before the first API request arrives Aug 13, 2021 at 12:08
  • That would make sense. Unfortunately I can't see where I could have done something wrong as Program.Main is not called before I make the first request.
    – Adagio
    Aug 13, 2021 at 12:13
  • That await Task.Delay guarantees that some request will arrive before the loop runs. At the very least, delay after the first execution. Or use a timer Aug 13, 2021 at 12:13
  • I understand what you are saying and in the above mentioned scenario where I should load some data before the first request, I need to have the wait until after loading the data. The backgroundworker I'm working on currently just needs to run every day some time after midnight. But the problem is still that Program.Main is not called until after first request is called. So even if I had pushed the away Task.Delay code to after execution, it will still not be called until the first request is made. And since none of my code is running before Program.Main, no bugs in my code could cause this
    – Adagio
    Aug 13, 2021 at 12:24
  • If you want to load the data before the first request, do it in Startup and definitely before calling .Run(). Use the background service only to refresh the data. If you use ASP.NET Core's IMemoryCache check How do I put data in a MemoryCache on startup?. You can add the initial data in the Configure method Aug 13, 2021 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.