[英]Task from cancellation token?
Given a cancellation token, I'd like to create an awaitable task out of it, which is never complete but can be cancelled. 鉴于取消令牌,我想创建一个等待它的任务,这是永远不会完成但可以取消。 I need it for a pattern like this, which IMO should be quite common:
我需要这样的模式,IMO应该很常见:
async Task DoStuff(Task t, CancellationToken ct)
{
// t was made from TaskCompletionSource,
// both t and ct are beyond my control
Task t2 = TaskFromCancellationToken(ct);
await Task.WhenAny(t, t2);
// do stuff
}
The best idea I've got so far is this: 我到目前为止最好的想法是:
Task TaskFromCancelationToken(CancellationToken ct)
{
return Task.Delay(Timeout.Infinite, ct);
}
Is there a better way to make this logic happen? 是否有更好的方法来实现这种逻辑?
It's not extremely common, but it's common enough to be part of my AsyncEx library. 它并不是非常常见,但它通常足以成为我的AsyncEx库的一部分。 I use something like this:
我使用这样的东西 :
public static Task AsTask(this CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<object>();
cancellationToken.Register(() => tcs.TrySetCanceled(),
useSynchronizationContext: false);
return tcs.Task;
}
Task.Delay(Timeout.Infinite, cancellationToken)
The answer you suggest in your question is the best solution to my knowledge. 您在问题中提出的答案是我所知道的最佳解决方案。 Here's why:
原因如下:
The Task.Delay
approach is heavily used by a lot of folks as per my knowledge, and is also recommended on Microsoft blogs. 根据我的知识,很多人大量使用
Task.Delay
方法,并且在Microsoft博客上也推荐使用。 MSDN Example . MSDN示例 。
Why write code (including tests) yourself leveraging TaskCompletionSource
for converting a cancellation token to a task? 为什么要自己编写代码(包括测试),利用
TaskCompletionSource
将取消令牌转换为任务? It is preferable to leverage the standard libraries instead of reinventing the wheel; 最好是利用标准库而不是重新发明轮子; they are more likely to be bug free than your code.
它们比你的代码更容易出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.