如何获取异步方法的结果?

时间:2010-01-25 09:15:46

标签: .net asynchronous callback

当我用了很长时间的操作时,不阻止我的应用程序的UI:

Public Sub ButtonHandler() handles Button
    Dim auxDelegate as Action

    auxDelegate = New Action(AddressOf DoAction)
    auxDelegate.BeginInvoke(AddressOf EndAction,Nothing)
End Sub

Private Sub DoAction()
    ''# Do long time operations here
End Sub

Private Sub EndAction()
    ''# Update results here
End Sub

有没有办法获取DoAction的结果,以防它是一个函数而不是一个Sub,并在EndAction上使用那个结果定义一个类属性并将值放在那里?

例如,如果DoAction是这样的:

Private Function DoAction() As Boolean
    return True
End Sub

有一种方法可以在EndAction中获取DoAction的结果吗?

提前致谢!

1 个答案:

答案 0 :(得分:2)

Action是一个指向函数的指针,该函数不接受任何参数并且不返回任何值。如果您希望函数返回某个值,则需要使用不同的委托。例如,如果希望函数返回布尔值,则可以使用Func(Of Boolean)

Dim auxDelegate As Func(Of Boolean)

Public Sub ButtonHandler() handles Button
    auxDelegate = AddressOf DoAction
    auxDelegate.BeginInvoke(AddressOf EndAction, Nothing)
End Sub

Private Function DoAction() As Boolean
    Return True
End Function

Private Sub EndAction(ByVal ar As IAsyncResult)
    ' call EndInvoke on the delegate to obtain the result
    Dim result As Boolean = auxDelegate.EndInvoke(ar)
End Sub