Parallel.invoke 取消令牌
使用 Parallel.Invoke 时,您可以传入包含 cancelationToken 的 ParallelOptions。是否可以在调用中使用该令牌来确定是否应该退出?是否应该在操作中使用对 CancellationTokenSource 的引用?
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
Parallel.Invoke(po,
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 1"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 2"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 3"); cts.Cancel(); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 4"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 5"); })
);
更新:取消发生得太晚了。我是在调用的方法之外执行此操作的。
注意:如果取消发生得足够快,Parallel.Invoke 将抛出异常,否则 inoked 方法将毫无失败地退出。
When using Parallel.Invoke, you're able to pass in ParallelOptions which includes a cancelationToken. Is it possible to use that token in the invocations to determine if exiting should occur? Should a reference to the CancellationTokenSource be used from within the actions?
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
Parallel.Invoke(po,
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 1"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 2"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 3"); cts.Cancel(); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 4"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 5"); })
);
Update: The cancellation was happening too late. I was doing it outside of the invoked methods.
Note: If the cancellation happens soon enough, the Parallel.Invoke will throw, but otherwise the inoked methods will exit without fail.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。例如:
特别是,您可以将取消标记传递到其他方法中,这些方法可能会将其传播到异步任务。
Yes. For example:
In particular, you could pass the cancellation token into other methods which may propagate it to asynchronous tasks.
msdn上有一个相当好的例子。
看来您既可以查询状态又可以使用cancelToken向调度程序发出信号。
http://msdn.microsoft.com/en-us/library/dd997364.aspx
There is a fairly good example on msdn.
it seems you can both query the status and use the cancellationToken to signal the scheduler.
http://msdn.microsoft.com/en-us/library/dd997364.aspx