取消令牌来源示例 [英] Cancellation Token source example

查看:71
本文介绍了取消令牌来源示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行一些异步操作,并且我想使用CancellationToken停止运行异步任务(如果例如用户请求的话).为了做到这一点,有一个字典是我的一个好习惯,通过它我可以找到正确的线程以停止正确的操作?我当前正在查看的是以下内容:

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?

例如,说用户使用线程{B}在数据库内部的集合{A}上执行了一些非常宽松的操作.然后,他取消了该操作,然后继续从另一个线程对集合{A}使用另一个冗长的操作.我应该为当前 CancellationToken 使用全局变量吗?

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 ?

推荐答案

通常,每个操作可以取消一个 CancellationTokenSource .您将CancellationTokenSource传递给可能需要取消操作( cts.Cancel())及其 CancellationToken ( cts.Token )的每个人给所有需要了解取消的人.

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.

这篇关于取消令牌来源示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆