How to use the CancellationToken property? How to use the CancellationToken property? multithreading multithreading

How to use the CancellationToken property?


You can implement your work method as follows:

private static void Work(CancellationToken cancelToken){    while (true)    {        if(cancelToken.IsCancellationRequested)        {            return;        }        Console.Write("345");    }}

That's it. You always need to handle cancellation by yourself - exit from method when it is appropriate time to exit (so that your work and data is in consistent state)

UPDATE: I prefer not writing while (!cancelToken.IsCancellationRequested) because often there are few exit points where you can stop executing safely across loop body, and loop usually have some logical condition to exit (iterate over all items in collection etc.). So I believe it's better not to mix that conditions as they have different intention.

Cautionary note about avoiding CancellationToken.ThrowIfCancellationRequested():

Comment in question by Eamon Nerbonne:

... replacing ThrowIfCancellationRequested with a bunch of checks for IsCancellationRequested exits gracefully, as this answer says. But that's not just an implementation detail; that affects observable behavior: the task will no longer end in the cancelled state, but in RanToCompletion. And that can affect not just explicit state checks, but also, more subtly, task chaining with e.g. ContinueWith, depending on the TaskContinuationOptions used. I'd say that avoiding ThrowIfCancellationRequested is dangerous advice.


You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle

var cancelToken = new CancellationTokenSource();Task.Factory.StartNew(async () => {    await Task.Delay(10000);    // call web API}, cancelToken.Token);//this stops the Task:cancelToken.Cancel(false);

Anther solution is user Timer in Xamarin.Forms, stop timer when app goto backgroundhttps://xamarinhelp.com/xamarin-forms-timer/


You can use ThrowIfCancellationRequested without handling the exception!

The use of ThrowIfCancellationRequested is meant to be used from within a Task (not a Thread).When used within a Task, you do not have to handle the exception yourself (and get the Unhandled Exception error). It will result in leaving the Task, and the Task.IsCancelled property will be True. No exception handling needed.

In your specific case, change the Thread to a Task.

Task t = null;try{    t = Task.Run(() => Work(cancelSource.Token), cancelSource.Token);}if (t.IsCancelled){    Console.WriteLine("Canceled!");}