2012-05-16 33 views
1

以前我在parallel.foreach vs Task.Factory.StartNew上收到了一些很好的建议。我已经实施了两者,并对两者的效率感到惊讶。我使用以下链接http://msdn.microsoft.com/en-us/library/dd997415.aspx来尝试理解异常,并将其合并到通知中,以便任何因任何原因程序将检测到任务而停止。有没有什么明确的方法来做到这一点,没有wait()或waitall这将绑定接口和其他任务在同一时间运行。如果过早停止并行任务,可以捕获并行任务

在FileParser.Module1.Main

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

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

,但我没有得到任何确认的过程:

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 

现在我试图用一个按钮调用和功能测试它停止。此外,如果使用parallel.foreach

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

回答

1

Catch不赶在Task抛出的异常,因为StartNew()不会阻塞等等Catch不活跃时再抛出异常。

如果您想在Task完成后执行某些操作,则可以使用ContinueWith()的重载之一。它们中的一些允许您指定继续运行的准确时间:只有当任务成功完成,出现故障或取消(或其组合)时才会执行。

+0

你能解释一下block..do你的意思是在startnew()之后有waitall()...如果我试图创建更多的任务,它会变得没有反应。 – vbNewbie

+0

我不是说你应该阻止使用'Wait()',这确实意味着你的应用程序会变得没有响应。就像我说的,改用'ContinueWith()'。 – svick

+0

好吧,我明白了,所以当完成分配的过程后,任务会继续执行某些操作,因此如果它在进程内失败,它将会陷入异常;对? – vbNewbie