taskToRun,...) 我测试了两种-6ren">
gpt4 book ai didi

c# - 了解 C# 中具有 "ContinueWith"行为的异步/等待与等待

转载 作者:太空狗 更新时间:2023-10-29 17:53:14 25 4
gpt4 key购买 nike

一种方法是标准的异步方法,像这样:

private static async Task AutoRetryHandlerAsync_Worker(Func<Task<bool>> taskToRun,...)

我测试了两种实现方式,一种使用await,另一种使用.Wait()

这两个实现根本不相等,因为相同的测试在 await 版本中失败,但在 Wait() 中却没有。

此方法的目标是“执行输入函数返回的任务,并通过执行相同的函数重试直到它起作用”(有限制,如果达到一定的尝试次数则自动停止)。

这个有效:

private static async Task AutoRetryHandlerAsync_Worker(Func<Task<bool>> taskToRun,...)
{
try {
await taskToRun();
}
catch(Exception)
{
// Execute later, and wait the result to complete
await Task.Delay(currentDelayMs).ContinueWith(t =>
{
// Wait for the recursive call to complete
AutoRetryHandlerAsync_Worker(taskToRun).Wait();
});

// Stop
return;
}
}

还有这个(使用 async t =>await 的用法而不是 t => 的用法。 Wait() 根本不起作用,因为在执行最终 return; 之前不会等待递归调用的结果:

private static async Task AutoRetryHandlerAsync_Worker(Func<Task<bool>> taskToRun,...)
{
try {
await taskToRun();
}
catch(Exception)
{
// Execute later, and wait the result to complete
await Task.Delay(currentDelayMs).ContinueWith(async t =>
{
// Wait for the recursive call to complete
await AutoRetryHandlerAsync_Worker(taskToRun);
});

// Stop
return;
}
}

我试图理解为什么这个简单的改变确实改变了一切,当它应该做完全相同的事情时:WAITING ContinueWith 完成。

如果我提取由 ContinueWith 方法运行的任务,我会看到传递给“ranToCompletion”的 ContinueWith 函数的状态内部 await 返回完成之前.

为什么?不是应该等待吗?


具体的可测试行为

public static void Main(string[] args)
{
long o = 0;
Task.Run(async () =>
{
// #1 await
await Task.Delay(1000).ContinueWith(async t =>
{
// #2 await
await Task.Delay(1000).ContinueWith(t2 => {
o = 10;
});
});
var hello = o;
});


Task.Delay(10000).Wait();
}

为什么 var hello = o; 在 o=10 之前到达?

#1 await 不是应该在执行可以继续之前挂起吗?

最佳答案

lambda 语法掩盖了您 ContinueWith(async void ...) 的事实。

async void 方法不会被等待,它们抛出的任何错误都不会被观察到。

对于您的基本问题,无论如何都不推荐从捕获中重试。太多了,catch block 应该很简单。直截了本地重试所有异常类型也很可疑。您应该知道哪些错误可以保证重试,让其余的通过。

追求简单性和可读性:

while (count++ < N)
{
try
{
MainAction();
break;
}
catch(MoreSpecificException ex) { /* Log or Ignore */ }

Delay();
}

关于c# - 了解 C# 中具有 "ContinueWith"行为的异步/等待与等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43542654/

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