Cancellation Token source example

瘦欲@ 提交于 2021-02-05 05:11:54

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/28458314/cancellation-token-source-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!