gpt4 book ai didi

c# - 等价于 ContinueWith(delegate, CancellationToken) with await continuation

转载 作者:可可西里 更新时间:2023-11-01 08:45:02 24 4
gpt4 key购买 nike

我有这种情况:

private Task LongRunningTask = /* Something */;

private void DoSomethingMore(Task previousTask) { }

public Task IndependentlyCancelableSuccessorTask(CancellationToken cancellationToken)
{
return LongRunningTask.ContinueWith(DoSomethingMore, cancellationToken);
}

特别是,我感兴趣的行为在 MSDN's page about Continuation Tasks 中有详细说明在以下条款中:

A continuation goes into the Canceled state in these scenarios:

上面的代码有效。但是,我正在将尽可能多的延续转换为使用 await 关键字。

是否有使用 await 的等效项允许在等待的任务完成之前取消继续?

最佳答案

下面应该可以做到,尽管它看起来有点笨拙:

private Task LongRunningTask = /* Something */;

private void DoSomethingMore() { }

public async Task IndependentlyCancelableSuccessorTask(
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
await Task.WhenAny(LongRunningTask, tcs.Task);

cancellationToken.ThrowIfCancellationRequested();
DoSomethingMore();
}

[更新] 根据 svick 的建议,这里它被塑造成一个助手,基于 Stephen Toub 的 Implementing Then with Await图案:

public static class TaskExt
{
/// <summary>
/// Use: await LongRunningTask.Then(DoSomethingMore, cancellationToken)
/// </summary>
public static async Task Then(
this Task antecedent, Action continuation, CancellationToken token)
{
await antecedent.When(token);
continuation();
}

/// <summary>
/// Use: await LongRunningTask.When(cancellationToken)
/// </summary>
public static async Task When(
this Task antecedent, CancellationToken token)
{
token.ThrowIfCancellationRequested();

var tcs = new TaskCompletionSource<Empty>();
using (token.Register(() => tcs.TrySetCanceled()))
await Task.WhenAny(antecedent, tcs.Task);

token.ThrowIfCancellationRequested();
}

struct Empty { };
}

也许第一个 ThrowIfCancellationRequested() 是多余的,但我还没有彻底考虑所有的边缘情况。

关于c# - 等价于 ContinueWith(delegate, CancellationToken) with await continuation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com