How to ‘await’ raising an EventHandler event

Edit: This doesn’t work well for multiple subscribers, so unless you only have one I wouldn’t recommend using this.


Feels slightly hacky – but I have never found anything better:

Declare a delegate. This is identical to EventHandler but returns a task instead of void

public delegate Task AsyncEventHandler(object sender, EventArgs e);

You can then run the following and as long as the handler declared in the parent uses async and await properly then this will run asynchronously:

if (SearchRequest != null) 
{
    Debug.WriteLine("Starting...");
    await SearchRequest(this, EventArgs.Empty);
    Debug.WriteLine("Completed");
}

Sample handler:

 // declare handler for search request
 myViewModel.SearchRequest += async (s, e) =>
 {                    
     await SearchOrders();
 };

Note: I’ve never tested this with multiple subscribers and not sure how this will work – so if you need multiple subscribers then make sure to test it carefully.

Leave a Comment