Devin Harris
Devin Harris

Reputation: 23

Do I need to explicitly create a cancellation token source with IHostedService?

Is the internal implementation of the library supplying me with a cancellation token source, or do I need to create my own?

I'm reading the documentation and it seems like I would need to create my own source in the caller method, then pass the token to the service.

Upvotes: 2

Views: 453

Answers (2)

Guru Stron
Guru Stron

Reputation: 142288

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.

Upvotes: 1

Adam
Adam

Reputation: 3847

If you are using the AddHostedService<T> extension method to add the service, then it will be supplied with a stopping token that will be cancelled if/when the host is gracefully terminated.

If for some reason you are calling the service through some other manual approach (i.e. testing), then you would want to provide it a cancellation token.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionhostedserviceextensions.addhostedservice

Upvotes: 0

Related Questions