I'm trying to implement a hosted service and I was wondering what I am expected to do with the CancellationToken in the IHostedService.StartAsync
call.
There is quite a lot in the Microsoft documentation about the cancellation token in StopAsync
being essentially a timeout (5s by default) that means graceful shutdown is supposed to happen within a reasonable timeframe.
But regarding the token in StartAsync
, there is not much information. If anything, the documentation specifies that the implementation shouldn't await on long running initialisation processes and should just return a long running task.
So if I support cancellation, should I pass the cancellation token to whatever creates that long running task? If yes, isn't cancelling this token a dumber version of StopAsync
? Why would the framework ever do this?
And indeed, in Microsoft's own abstract BackgroundService, the implementation for StartAsync
actually completely ignores that token and creates a new one which will be cancelled on call to StopAsync
...
So am I to think that the whole point of that initial token passed by the framework is actually to be used in blocking
initialisation processes nonetheless (despite the doc advising against it) by overriding the virtual BackgroundService.StartAsync
method? e.g.
public class MyBackgroundService : BackgroundService
{
public override Task StartAsync(CancellationToken cancellationToken)
{
// Block the thread for initialisation with cancellation (replace Task.Delay by actual initialisation)
Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).GetAwaiter().GetResult();
// Start the long running task proper
return base.StartAsync(cancellationToken);
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
// some long running process (write some actual background running code here)
return Task.Factory.StartNew(_ => {while(!stoppingToken.IsCancellationRequested){}}, null, stoppingToken);
}
}