考虑一下 example。它展示了如何创建具有取消支持的任务。
我也在做类似的事情:
Task.Run(()=>{while (!token.IsCancellationRequested()) {...}}, token);
我的问题:
Task.Run
调用呢?if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();
这段代码的目的是什么?为什么不只是return
的方法?
发布于 2015-02-17 00:32:27
Task.Run
,如果令牌在任务启动前被取消,它将永远不会启动,从而节省资源(我的意思是不创建线程等)。Canceled
,而是RanToCompletion
。很明显这不是你所期望的。或者,您可以抛出以OperationCanceledException
为参数的CancellationToken
,这将使Task.Status
成为Canceled
,但这是一种艰难而冗长的方式。token.ThrowIfCancellationRequested
是简洁的。
您可以简单地使用token.ThrowIfCancellationRequested();
,不需要检查token.IsCancellationRequested
。ThrowIfCancellationRequested
方法已经这样做了。
https://stackoverflow.com/questions/28557506
复制相似问题