catching parallel tasks if they stop prematurely

2019-08-01 14:14发布

问题:

I received some good advice previously on parallel.foreach vs Task.Factory.StartNew. I have implemented both and have been surprised with the efficiency of both. I used the following link http://msdn.microsoft.com/en-us/library/dd997415.aspx to try and understand exceptions and incorporate it to be notified if a task stops for any reason the program will detect it. Is there any definitive way to do this without wait() or waitall which will tie off the interface and other tasks running at the same time.

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

now I tried testing it with a button call and the function:

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

in FileParser.Module1.Main

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

but I am not getting any confirmation that the process stopped. Also if using the parallel.foreach

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

回答1:

Your Catch doesn't catch exceptions thrown by the Task, because StartNew() doesn't block and so the Catch is not active anymore when the exception is thrown.

If you want to do something after the Task finishes, you can use one of the overloads of ContinueWith(). Some of them allow you specify when exactly should the continuation run: only if the task finished successfuly, if it was faulted or cancelled (or a combination of them).