我之前收到了一些关于 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))