我有一个分配了异步执行任务的组件。完成后,它将触发两个事件中的一个来表示成功或失败。我需要将所有这些转换为同步调用:
Public Function AssignTask(o As Object) as Boolean
Dim component As New X.Y.Z.Component()
component.DoSomethingWith(o)
AddHandler component.OnSuccess, AddressOf OnSuccess
AddHandler component.OnError, AddressOf OnError
Return True 'Need to return success or not.
End Sub
Private Sub OnSuccess(sender As Object, e As System.EventArgs)
'Success! :)
End Sub
Private Sub OnError(sender As Object, e As System.EventArgs)
'Error! :(
End Sub
我很困惑,至于如何让事件触发主方法成功或失败。
谢谢!
答案 0 :(得分:1)
你可以做这样的事情(这不是线程安全的,所以如果你为不同的线程调用它会不会很好)
Private _completedFlag As Boolean
Private _completionResult As Boolean
Public Function AssignTask(o As Object) as Boolean
Dim component As New X.Y.Z.Component()
_completedFlag = False
AddHandler component.OnSuccess, AddressOf OnSuccess
AddHandler component.OnError, AddressOf OnError
component.DoSomethingWith(o)
Do Until _completedFlag
'wait
Loop
Return _completionResult
End Sub
Private Sub OnSuccess(sender As Object, e As System.EventArgs)
_completionResult = True
_completedFlag = True
End Sub
Private Sub OnError(sender As Object, e As System.EventArgs)
_completionResult = False
_completedFlag = True
End Sub
在实际调用方法之前,我已将AddHandler移动到,因为它可能在连接处理程序之前完成