Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancellation Token source example

I'm doing some asynchronous operations and I would like to use CancellationToken to stop an async task from running if the user for example requests this. In order to do so is it a good practice to have a Dictionary with which I can find the correct Thread in order to stop the correct operation? What I'm currently looking at is the following :

    public Dictionary<Thread, CancellationToken> CancellationTokenData;

Thus, if the user requests a cancellation on an operation it should behave correctly if I'm not wrong?

What are the best practices to do this?

For example say that the user executes some very lenghty operation on a set {A} inside the database using a Thread {B}. Then he cancels the operation and goes and uses another lengthy operation on set {A} from another thread. Should I use a global variable for the current CancellationToken ?

like image 709
Christo S. Christov Avatar asked Feb 11 '15 15:02

Christo S. Christov


1 Answers

Usually, you have one CancellationTokenSource per operation that is cancellable. You pass the CancellationTokenSource to everybody who may need to cancel the operation (cts.Cancel()), and its CancellationToken (cts.Token) to everyone who needs to be aware of the cancellation.

At this level of abstraction, you do not stop threads; you stop operations. The threads are merely implementation details.

Therefore, I do not think it's a good idea to map tokens to threads. If tasks are involved, it is a very bad idea, because there is no guarantee that each task actually runs on a new thread.

like image 90
Sebastian Negraszus Avatar answered Sep 28 '22 07:09

Sebastian Negraszus