我在异步 DelegateCommand(Prism 5)中捕获异常时遇到了很多麻烦。
在 ViewModel 的构造函数中:
cmdModificarPedido = New DelegateCommand(Of Object)(AddressOf OnModificarPedido, AddressOf CanModificarPedido)
在视图模型中:
Private _cmdModificarPedido As DelegateCommand(Of Object)
Public Property cmdModificarPedido As DelegateCommand(Of Object)
Get
Return _cmdModificarPedido
End Get
Private Set(value As DelegateCommand(Of Object))
SetProperty(_cmdModificarPedido, value)
End Set
End Property
Private Function CanModificarPedido(arg As Object) As Boolean
Return True
End Function
Private Async Sub OnModificarPedido(arg As Object)
Try
Await Task.Run(Sub()
Throw New Exception("My Exception")
End Sub)
NotificationRequest.Raise(New Notification() With {
.Title = "OK",
.Content = "Command OK"
})
Catch ex As Exception
NotificationRequest.Raise(New Notification() With {
.Title = "Error",
.Content = ex.Message
})
End Try
End Sub
为什么异常没有被捕获?我知道这是另一个线程,但无论如何它都应该被外部 Try...Catch 块捕获(Try Catch 外部:await Task.Run(())。
注意:它是 vb.net 代码,但 C# 解决方案也可以。
更新 2 一旦我知道我的调试器配置有问题(第一次机会例外),我写了一个更现实的例子,同样的问题:
Private Async Sub OnModificarPedido(arg As Object)
Try
Await Task.Run(Sub()
Try
throwMyException()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub)
NotificationRequest.Raise(New Notification() With {
.Title = "Pedido Modificado",
.Content = "Pedido " + pedido.numero.ToString + " modificado correctamente"
})
Catch ex As Exception
NotificationRequest.Raise(New Notification() With {
.Title = "Error",
.Content = ex.Message
})
End Try
End Sub
Public Async Sub throwMyException()
Throw New Exception("My Exception")
End Sub
现在当我按 F5 时它不会捕获异常。它在“throwMyException()”中中断,尽管它在 Try Catch 块内被调用,但它不会捕获异常。
重要提示:如果我删除“throwMyException”中的 Async 单词,它会捕获它!!!
我现在做错了什么?
谢谢