简体   繁体   English

取消令牌源示例

[英]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. 我正在做一些异步操作,我想使用CancellationToken来阻止异步任务运行,如果用户例如请求它。 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? 为了做到这一点,最好有一个Dictionary,我可以找到正确的Thread来停止正确的操作? 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}. 例如,假设用户使用线程{B}在数据库内的集合{A}上执行一些非常长的操作。 Then he cancels the operation and goes and uses another lengthy operation on set {A} from another thread. 然后他取消操作并继续使用来自另一个线程的集合{A}的另一个冗长的操作。 Should I use a global variable for the current CancellationToken ? 我应该为当前的CancellationToken使用全局变量吗?

Usually, you have one CancellationTokenSource per operation that is cancellable. 通常,每个可取消的操作都有一个CancellationTokenSource 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. 您将CancellationTokenSource传递给可能需要取消操作的所有人( cts.Cancel() ),并将CancellationTokencts.Token )传递给需要知道取消的每个人。

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. 如果涉及任务,这是一个非常糟糕的主意,因为无法保证每个任务实际上都在新线程上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM