Dabblernl
Dabblernl

Reputation: 16141

How to wait for an async call from an eventhandler

I have the following event handler:

  Private Async Sub DatabaseRestored(sender As RestoreBackupViewModel)
        _success = Await _applicationManager.ReinitializeAsync
    End Sub

The problem is that I really need to know if the ReinitializeAsync function has completed before initiating other actions. When I change the code to:

  Private Sub DatabaseRestored(sender As RestoreBackupViewModel)
        _success = _applicationManager.ReinitializeAsync.Result
    End Sub

The code deadlocks.

How to handle this?

Upvotes: 0

Views: 542

Answers (2)

Dabblernl
Dabblernl

Reputation: 16141

I solved it thus:

   Private Async Function DatabaseRestoredAsync() As Task
        _success = Await _applicationManager.ReinitializeAsync
    End Function

So, no event and eventhandler any more. Simply a call back (Func(Of Task)) that is passed to the class that otherwise would subscribe to the event an can now await it. Possible memory leaks seem not a concern at this point.

The class that otherwise would subscribe to the event now has code like:

Await _databaseRestoredCallback.Invoke()

instead of

RaiseEvent DatabaseRestored(Me)

The _databaseRestoredCallback field referencing the DatabaseRestoredAsync function.

Upvotes: 2

Chris Berlin
Chris Berlin

Reputation: 1087

Try this:

_success = _applicationManager.ReinitializeAsync.GetAwaiter().Result

Upvotes: 1

Related Questions