Is the internal implementation of the library supplying me with a cancellation token source, or do I need to create my own?
No, you will not be getting CancellationTokenSource
, only CancelationToken
's for StartAsync
/StopAsync
methods (to support graceful shutdown/interruption, some docs).
If need to cancel call to some service additionally you will need to create your own CancellationTokenSource
via CancellationTokenSource.CreateLinkedTokenSource
. Something along these lines:
class MyHostedService : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(1000); // for example
_ = someService.DoAsync(cts.Token);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(1000); // for example
await anotherService.DoAsync(cts.Token);
}
}
If you don't have custom cancellation logic then using passed cancellationToken
is enough.
Also consider using BackgroundService
base class, it encapsulates some of usual hosted service boilerplate code.