来自取消令牌的任务? [英] Task from cancellation token?
问题描述
给定一个取消令牌,我想从中创建一个可等待的任务,该任务永远不会完成但可以取消.我需要这样的模式,IMO 应该很常见:
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:
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?
推荐答案
这不是非常常见的,但它很常见,足以成为我AsyncEx 库.我使用 类似这样的:
It's not extremely common, but it's common enough to be part of my AsyncEx library. 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;
}
更新:最近,我建议使用类似 CancellationTokenTaskSource
,它可以正确处理所有生命周期,没有资源泄漏的可能性.
Update: These days, I recommend using something like CancellationTokenTaskSource
, which properly handles all lifetimes with no possibility of resource leaks.
这篇关于来自取消令牌的任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!