如何变换task.Wait(的CancellationToken)到等待说法? [英] How to transform task.Wait(CancellationToken) to an await statement?

查看:393
本文介绍了如何变换task.Wait(的CancellationToken)到等待说法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​, task.Wait()可以转化为等待任务。语义是不同的,当然,不过这大约是我怎么会去改变一个阻塞code与等待来异步code与等待

So, task.Wait() can be transformed to await task. The semantics are different, of course, but this is roughly how I would go about transforming a blocking code with Waits to an asynchronous code with awaits.

我的问题是如何将 task.Wait(的CancellationToken)到相应的计谋语句?

My question is how to transform task.Wait(CancellationToken) to the respective await statement?

推荐答案

要创建一个新的工作的再presents现有的任务,但有一个附加的取消标记非常简单。你只需要调用 ContinueWith 的任务,使用新的令牌,并传播其结果/例外的延续了身体。

To create a new Task that represents an existing task but with an additional cancellation token is quite straightforward. You only need to call ContinueWith on the task, use the new token, and propagate the result/exceptions in the body of the continuation.

public static Task WithCancellation(this Task task,
    CancellationToken token)
{
    return task.ContinueWith(t => t.GetAwaiter().GetResult(), token);
}
public static Task<T> WithCancellation<T>(this Task<T> task,
    CancellationToken token)
{
    return task.ContinueWith(t => t.GetAwaiter().GetResult(), token);
}

这允许你写 task.WithCancellation(的CancellationToken)来令牌添加到一个任务,然后你就可以计谋

This allows you to write task.WithCancellation(cancellationToken) to add a token to a task, which you can then await.

这篇关于如何变换task.Wait(的CancellationToken)到等待说法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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