简体   繁体   中英

How to restart BackgroundService from Controller

I created WcBackgroundService (inherit by BackgroundService) and I'm injecting it to OrdersController. When frontend API sends request on restart endpoint I'll execute Restart method from my worker.

As above, current solution doesn't restart service only create new instance of my background service and start it.

Below is my code

WcBackgroundService

public async Task Restart()
{
    await StopAsync(new CancellationToken());
    await StartAsync(new CancellationToken());
}

protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
     cancellationToken.Register(() =>
     {
         _logger.Debug($"Service {_serviceType} is stopping.");
     });

     while (!cancellationToken.IsCancellationRequested)
     {
         await DoWork();
     }
}

ConfigureServices in Startup:

..
services.AddSingleton<IWcBackgroundService, WcBackgroundService>();
..

Configure in Startup:

var wcBackgroundService = app.ApplicationServices.GetService<IWcBackgroundService>();
wcBackgroundService.StartAsync(new CancellationToken()).Wait();

You have to cancel on THE SAME token, which is passed at the start, only then will it cancel the background task.

You should implement cancellation in your task, cancel through the token which you properly pass through and store in somewhere, for example implement a task management service which you register as a singleton in your DI container (you can also get the token from your wcBackGroundService if you expose it through a property), then implement a controller endpoint let's say "RestartBackgroundTask" which get's the token or tokenSource from the singleton service and cancels it, then calls the start method again. You can move the task.Start into a separate function so you can all the same logic without code duplication.

Read about cancellationTokenSource

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM