如何在函数中等待事件被引发

时间:2017-09-18 14:42:40

标签: vb.net multithreading asynchronous

我有一个函数GetLogs,可以调用另一个函数GetHistoricalData。 GetHistoricalData在一个线程中运行,在它结束时,它会触发一个事件AsyncLoggingRequestFinished。我想要的是在GetLogs等待事件被提出。这是一个使思想更清晰的代码示例:

Private Sub GetLogs
    _historicalLogging = new HistoricalLogging()
    AddHandler _historicalLogging.AsyncLoggingRequestFinished, AddressOf _historicalLogging_AsyncLoggingRequestFinished
    _historicalLogging.GetHistoricalData("LogCategory")
   'I want to wait here and after the event raised, keep going
End Sub

Private Sub _historicalLogging_AsyncLoggingRequestFinished(ByVal sender As Object, ByVal e As AsyncRequestSuccessArgs)
    RemoveHandler _historicalLogging.AsyncLoggingRequestFinished, AddressOf _historicalLogging_AsyncLoggingRequestFinished
    For Each entry in _historicalLogging.Entries
        'DoSomething
    Next
End Sub

注意:HistoricalLogging是DLL中的对象。我无法更改该对象的任何代码

1 个答案:

答案 0 :(得分:0)

不是最好的方法,但它有效

Private Sub GetLogs()
    _historicalLogging = New HistoricalLogging()
    AddHandler _historicalLogging.AsyncLoggingRequestFinished, AddressOf _historicalLogging_AsyncLoggingRequestFinished
    _historicalLogging.GetHistoricalData("LogCategory")
    'I want to wait here and after the event raised, keep going
    Do Until EventRaisen
        Application.DoEvents()
    Loop
    EventRaisen = False
    'Code After The Event Has Raisen
End Sub
Dim EventRaisen As Boolean = False
Private Sub _historicalLogging_AsyncLoggingRequestFinished(ByVal sender As Object, ByVal e As AsyncRequestSuccessArgs)
    RemoveHandler _historicalLogging.AsyncLoggingRequestFinished, AddressOf _historicalLogging_AsyncLoggingRequestFinished
    For Each entry In _historicalLogging.Entries            
        EventRaisen = True
        'DoSomething
    Next
End Sub