【问题标题】:catching parallel tasks if they stop prematurely如果并行任务过早停止,则捕获它们
【发布时间】:2012-05-17 00:52:02
【问题描述】:

我之前收到了一些关于 parallel.foreach 与 Task.Factory.StartNew 的好建议。我已经实现了两者,并且对两者的效率感到惊讶。我使用以下链接http://msdn.microsoft.com/en-us/library/dd997415.aspx 来尝试理解异常并将其合并以在任务因任何原因停止程序将检测到它时得到通知。是否有任何明确的方法可以在没有 wait() 或 waitall 的情况下执行此操作,这将绑定接口和同时运行的其他任务。

Try
     pcounter += 1
     Dim factory As Task = Task.Factory.StartNew(AddressOf FileParser.Module1.Main)
        If factory.IsCompleted Then
            appLogs.constructLog("GT19 Task Completed", True, True)
        End If
        Button1.Text = pcounter.ToString & " processes started"
        If Not TextBox1.Text = "" Then
            Module1.inputfolder = TextBox1.Text
        End If


    Catch ae As AggregateException
        For Each ex In ae.InnerExceptions
            appLogs.constructLog(ex.Message.ToString & " ", True, True)
        Next
        Button1.Text = "ERROR RECEIVED"
    Catch ex As Exception
        If ex.Message.Contains("cannot access") Then
            appLogs.constructLog(ex.Message.ToString & " ", True, True)
        End If
        appLogs.constructLog(ex.Message.ToString & " ", True, True)
        appLogs.constructLog(" Cancelling process ", True, True)
    Finally
        Module1.ctsources.Cancel()
    End Try

现在我尝试使用按钮调用和函数对其进行测试:

   Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
  Module1.ctsources.Cancel()
  Button2.Text = "process stopped"

在 FileParser.Module1.Main 中

If ct.IsCancellationRequested Then
                sendErrorEmail()
                Exit Sub
End If

但我没有得到任何进程停止的确认。另外如果使用parallel.foreach

        Dim po As New ParallelOptions
        po.MaxDegreeOfParallelism = 3
        Parallel.ForEach(fileLists, po, Sub(page) processFile(page))

【问题讨论】:

    标签: vb.net task-parallel-library


    【解决方案1】:

    您的Catch 不会捕获Task 抛出的异常,因为StartNew() 不会阻塞,因此当抛出异常时Catch 不再处于活动状态。

    如果您想在Task 完成后做某事,您可以使用ContinueWith() 的重载之一。其中一些允许您指定继续运行的确切时间:仅当任务成功完成、出现故障或取消(或它们的组合)时。

    【讨论】:

    • 你能解释一下block..你的意思是在startnew()之后有waitall()吗......如果是这样,如果我尝试创建更多任务,它会不会变得无响应。
    • 我并不是建议您使用Wait() 阻止,这确实意味着您的应用程序将变得无响应。就像我说的,改用ContinueWith()
    • 好的,我明白了,所以当任务完成分配的进程后,让任务继续做某事,因此如果它在进程中失败,它将被捕获到异常中;对吗?
    猜你喜欢
    • 2021-10-03
    • 2014-08-01
    • 2022-12-16
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多