【问题标题】:Does ContinueWith not handle Async callbacks?ContinueWith 不处理异步回调吗?
【发布时间】:2016-08-08 01:13:25
【问题描述】:

我看到了 Stephen Cleary 关于Startnew being dangerous 以及continuewith is also dangerous 的博客。我想在这里使用它来避免在出现异常的情况下必须编写一个 try finally 来调用 NSubstitute 。我发现测试在不应该通过的时候通过了,然后注意到异常被抛出,但它没有通过测试发出 nunit 信号。

ContinueWith 在异步函数方面的行为与 Task.Startnew 类似吗?我注意到这个简化的等价物不会在 Nunit 3 中引发内部异常。

[Test]
public async Task SimpleTest()
{
    await Task.Delay(10).ContinueWith( async t =>
    {
        await Task.Run(()=>{throw new Exception();});
    });
}

【问题讨论】:

    标签: c# async-await c#-5.0


    【解决方案1】:

    ContinueWith 不理解 async lambdas。除了传递任务调度程序之外,您还需要使用Unwrap

    我想在这里使用它以避免在出现异常的情况下必须编写 try finally 来调用 NSubstitute。

    我不明白这个要求。为什么这不起作用?

    await Task.Delay(10);
    await Task.Run(() => { throw new Exception(); });
    

    【讨论】:

    • 在示例中,延迟只是一些“工作”。在我的实际测试中,工作可能会引发异常,因此我必须先用 try catch 包装等待,然后调用 NSubstitute received(在需要使用 await 的承诺任务函数上,由 task.run 表示我的例子)。看起来它会比使用 continuewith 多一点代码。
    • 重申一下,对ContinueWith正确 调用如下所示:await Task.Delay(10).ContinueWith(_ => Task.Run(...), CancellationToken.None, TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default).Unwrap(); 我认为try { await Task.Delay(10); } finally { await Task.Run(...); } 更简洁。
    • 如果是这样(我绝对不知道完全正确的 continuewith 用法),我会同意。我最终使用 await 和 try/catch/finally 创建了一个小型帮助程序库,它类似于 javascript 承诺,让我可以使用 doThis.finally(somethingelse) 之类的东西。这样我就避免了 continuewith 并避免在我的测试中写 try finally 。感谢斯蒂芬的帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2014-12-03
    • 2021-04-16
    • 2021-06-17
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多