使用CancellationTokenSource

编程入门 行业动态 更新时间:2024-10-23 19:21:31
本文介绍了使用CancellationTokenSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人可以举一个例子,我应该在哪里使用下一个方法有三个参数。

Can somebody give an example, where I should use the next method with three arguments.

var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; Task.Factory.StartNew(MyTask, token, token);

你能解释请,为什么我们需要一个第三个参数?

Could you explain please, why we need a third argument?

推荐答案

有没有超载 StartNew 的是 StartNew(行动的CancellationToken,的CancellationToken)。最有可能的,这里被调用的方法是 StartNew(动作<对象&gt ;,对象的CancellationToken)。

There is no overload of StartNew that is StartNew(Action, CancellationToken, CancellationToken). Most likely, the method being called here is StartNew(Action<object>, object, CancellationToken).

这超负荷开始行动,通过在所提供的对象(第二个参数),作为该行动的说法。

This overload starts the Action, passing in the provided object (second argument) as the argument for this Action.

我只能假设的原因是,这样的行动可以参加合作解约过程的CancellationToken 提供。换句话说,它不仅允许任务被取消,通过令牌合作,但你可以为了尽快退出运行,并可能避免ThreadAbortedException使用它的行动。

I can only assume the reason for this is so that the Action can participate in the cooperative cancelling process that CancellationToken provides. In other words, it allows for not only the Task to cooperate in cancellation via the token, but you can use it in the Action in order to quit execution ASAP and possibly avoid a ThreadAbortedException.

var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; Task.Factory.StartNew(x => { var token = (CancellationToken)x; for(var item in ReallyBigCollection){ Process(item, token); if(token.IsCancellationRequested) return; } }, token, token);

没有太多的理由有一个的CancellationToken,除非你打算使用它。

There isn't much reason to have a CancellationToken unless you're going to use it.

更多推荐

使用CancellationTokenSource

本文发布于:2023-11-08 07:02:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568672.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CancellationTokenSource

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!