如果并行任务过早停止,则捕获并行任务 [英] catching parallel tasks if they stop prematurely
问题描述
我之前收到了一些关于 parallel.foreach 与 Task.Factory.StartNew 的好建议.我已经实现了两者,并且对两者的效率感到惊讶.我使用了以下链接 http://msdn.microsoft.com/en-us/library/dd997415.aspx 尝试理解异常并将其合并,以便在程序将检测到的任何原因导致任务停止时通知它.是否有任何明确的方法可以在不使用 wait() 或 waitall 的情况下执行此操作,这将绑定接口和同时运行的其他任务.
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"
在 FileParser.Module1.Main 中
in FileParser.Module1.Main
If ct.IsCancellationRequested Then
sendErrorEmail()
Exit Sub
End If
但我没有得到任何进程停止的确认.另外如果使用parallel.foreach
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))
推荐答案
您的 Catch
不会捕获 Task
抛出的异常,因为 StartNew()
不会阻塞,因此当抛出异常时 Catch
不再处于活动状态.
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.
如果您想在 Task
完成后做某事,您可以使用 ContinueWith()
.其中一些允许您指定继续运行的确切时间:仅当任务成功完成、出现故障或取消(或它们的组合).
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).
这篇关于如果并行任务过早停止,则捕获并行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!