Search code examples
c#backgroundworker

Where does the cancellation token come from in a background worker?


I am using a background and but default I have this 2 methods:

public override async Task StartAsync(CancellationToken cancellationToken)
{
}

public override async Task StopAsync(CancellationToken cancellationToken)
{
}

I have another method that do something and if there is some error, I would like to stop the service.

private MyMethod()
{
    //do something
    if(some error)
    {
         StopAsync(???)
    }
}

But My doubt is which cancellation token I have to use as parameter, because I don't know when is called the StartAsync() and StopAsync() methods, and I don't know if the cancellation token is the same object when they are called or they are different objects.

If it is the same method, where could I find this method to use as parameter when I try to call the StopAsync() method?

In summary, I would like to know which is the best way to stop the service if something is wrong and I decide to stop it.

Thanks.


Solution

  • Cancellation token is there to cancel only async operation (Task). Nothing more to that.

    So, if you want to be able to cancel started operation, let's say StopAsync you just create CancellationTokenSource and pass it's property Token to a method and in case cancellation of that operation is needed, you just call Cancel method, which would cancel the StopAsync. It's just about cancelling particular operations.

    If you do not want to have this possibility, just pass default there :)