任务从取消标记? [英] Task from cancellation token?

查看:166
本文介绍了任务从取消标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于取消的道理,我想创建一个awaitable任务了吧,这是从来没有完成,但可以取消。我需要它这样的模式,这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 库。我使用的<一个href="https://github.com/StephenCleary/AsyncEx/blob/master/Source/Nito.AsyncEx%20(NET45%2C%20Win8%2C%20WP8%2C%20WPA81)/CancellationTokenExtensions.cs"相对=nofollow>像这:

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();
    cancellationToken.Register(() => tcs.TrySetCanceled(),
        useSynchronizationContext: false);
    return tcs.Task;
}

这篇关于任务从取消标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆