检测任务中的错误并恢复

Detecting errors in tasks and reviving

我需要 运行,比方说,20 个并行任务。正在调用的任务函数是一个长 运行ning 函数,可能会产生错误。我想从调用者那里检测到并恢复任务。

虽然我知道处理异常 "inside the task" 并重新 运行 任务是一个解决方案,但我也在考虑是否有办法从调用者本身检测到这一点 运行 再次失败的任务。当我恢复任务时,它应该属于 20 个任务 运行ning 的范围,以便调用进程继续等待所有任务 运行ning,包括通过 Await Task.WhenAll(tasks)[ 恢复的新任务=15=]

调用方的代码创建了 20 个不同的任务并等待它们全部完成。

    Try
        watch = New Stopwatch
        watch.Start()
        cs = New CancellationTokenSource
        Timer1.Enabled = True
        Dim tasks = Enumerable.Range(1, 20).Select(Function(i) Task.Run(Function() GetAndProcessMessagesAsync(cs.Token)))
        Await Task.WhenAll(tasks)
    Catch ex As Exception
        MsgBox(ex.Message)
        Timer1.Enabled = False
    End Try

PS:我已经检查了以下链接的解决方案,但没有找到适合我尝试的方法。但肯定会认为另一种方法可能是使用 TaskContinuationOptions 选项,但我真的不确定如何以及在哪里适合我上面的代码。

Task Parallel Library - How do you get a Continuation with TaskContinuationOptions.OnlyOnCanceled to Fire?

catching parallel tasks if they stop prematurely

我认为在 Task 内进行是最好的选择,但这并不意味着您必须更改 GetAndProcessMessagesAsync。代码可能如下所示:

Async Function RetryAsync(func As Func(Of Task)) As Task
    While True
        Try
            Await func()
        Catch
            ' TODO: don't catch all exceptions all the time
        End Try
    End While
End Function

…

Dim tasks = Enumerable.Range(1, 20).Select(
    Function(i) Task.Run(
        Function() RetryAsync(
            Function() GetAndProcessMessagesAsync(cs.Token))))

此外,如果 GetAndProcessMessagesAsync 是真正的异步,您可能不需要 Task.Run