2016-08-16 49 views
0

这是一个Windows窗体应用程序,其中我有一个特定的窗体。在这个表单上,我显示了一些应该在后台异步执行的处理过程。除了当我尝试处理在后台处理中捕获到的异常时,它的所有功能都很好。...从子向异步调用抛出异常

这是调用异步函数的子表单中的代码,该异步函数位于包含所有后台处理代码:

Public Async Sub BasicProcessing() 
     Try 
      Dim processTarget As Action(Of Integer) 
      processTarget = AddressOf UpdatePulseProcessing 
      myProgress = New Progress(Of Integer)(processTarget) 
      myCount.Vehicles = Await ProcessmyCountFile(myCount, myProgress) 

      If OperationCanceledByUser = True Then 
       Exit Sub 
      End If 
    Catch ex As Exception 
     MessageBox.Show(Me, "Unable to update count." _ 
         & Environment.NewLine & ex.Message, _ 
         "Error updating count", MessageBoxButtons.OK, MessageBoxIcon.Error) 
     Exit Sub 
    End Try 
End Sub 

这是异步函数调用,这是在一个独立的模块:

Public Function ProcessmyCountFile(CountToProcess As Count, ByVal ProgressObject As IProgress(Of Integer)) As Task(Of List(Of Vehicle)) 
    myProgressObject = ProgressObject 
    basicToken = New CancellationTokenSource 

    Try 
     Return CType(Task(Of List(Of Vehicle)).Run(Function() 

                 If basicToken.IsCancellationRequested Then 
                  Return Nothing 
                  Exit Function 
                 End If 

                 myCountFile = CountToProcess 
                 MyVehicles = New List(Of Vehicle) 

                 'All that is important in here to note is a call to a regular sub within this module 
                 CreateVehicles() 

                 Return MyVehicles 
                End Function, basicToken.Token), Global.System.Threading.Tasks.Task(Of List(Of Global.STARneXt.Vehicle))) 
    Catch ex As Exception 
     Throw New Exception(ex.Message) 
     Return Nothing 
    End Try 

End Function 

Public Sub StopProcess() 
    If Not basicToken Is Nothing Then 
     basicToken.Cancel() ' We tell our token to cancel 
    End If 
End Sub 

这是由异步函数调用的常规子:

Private Sub CreateVehicles() 

    Try 

     'In here are calls to other regular subs within the same module, let's just call them A and B 

    Catch ex As Exception 
     StopProcess() 
     Throw New Exception("Error creating vehicles at pulse " & pulsePointer & ". " & ex.Message) 
    End Try 

End Sub 

当我使用我知道的数据运行此代码时,最终会在子B中生成一个错误,该错误确实会传播,直至由异步函数直接调用的方法... 所以当在VS中运行时,它将停止在“抛出新的异常(”错误在脉冲创建车辆“& pulsePointer &”。 “& ex.Message)”,用含有由子B.抛出的消息的消息

这是调试器说在该行上:

类型的异常“System.Exception的”发生在MyProject.exe但 未在用户代码中处理。附加信息:在脉冲......时创建 车辆时出错。[错误消息传播时被称为 ]。算术运算导致溢出。

然后奇怪的是,在调试器中,如果我点击“Step Into”,它会返回到我的表单中调用异步函数的子窗口,它显示GUI上的消息框。

那么如何获得这个自动返回到原始表单代码来显示消息框呢?为什么它停止在没有继续传播的地方?

仅供参考,我确实发现this question,但它最终没有帮助。

+0

这只是一个调试器怪癖。你可以告诉VS不要打破这种类型的异常。 –

+0

@StephenCleary,但不会让它在任何时候遇到溢出异常不会中断吗?我不想那样,对吧?你是说当我将它作为已安装的应用程序而不是在调试器中运行时,它应该按预期工作? – Andarta

+1

是的,它可能会在调试器外正常工作。 –

回答

0

@StephenCleary是对的 - 我为我的项目创建了一个新的安装,并且在安装的版本中,我收到了带有预期错误消息的消息框。

调试器部分的奇怪行为,有点令人沮丧,但无论如何,我很高兴我的问题中列出的代码确实有效。