Prism Async DelegateCommand

时间:2016-12-28 09:47:06

标签: asynchronous prism delegatecommand

我在async DelegateCommand(Prism 5)中捕获异常有很多麻烦。

在ViewModel的构造函数中:

cmdModificarPedido = New DelegateCommand(Of Object)(AddressOf OnModificarPedido, AddressOf CanModificarPedido)

在ViewModel中:

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 outside of: await Task.Run(())捕获。

enter image description here

注意:它是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字,它确实会抓住它!

我现在做错了什么?

谢谢

1 个答案:

答案 0 :(得分:0)

您发布的原始代码没有问题 - 调试器只是在您的代码执行之前捕获异常,这是完全正常的。

使用更新的代码,问题是使用Async Sub。无法直接从Async Sub方法捕获异常。您应该使用(非AsyncSubAsync Func(of Task)代替。这个原则在我的MSDN article on async best practices中称为“避免异步空白”。

相关问题