有人可以举一个例子,我应该在哪里使用下一个方法有三个参数。
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
发布评论