Waiting for an event handler

So here deleagte and event

public delegate Task SomeEventHandler(SomeEventArgs e); ... public event SomeEventHandler OnSomething; 

Subscribers (several)

 some.OnSomething += DoSomething; ... public async Task DoSomething(SomeEventArgs e) { await SomethingElse(); eA = true; } 

Event call

 if (this.OnSomething != null) await this.OnSomething(args); // Here args.A is false // It should be true 

The problem is that the last part continues even when DoSomething is not completed. What is the problem?

+6
source share
1 answer

The problem is that multiple instances of SomeEventHandler , so multiple Task values ​​are created. The await call only works on one of them, so somewhat randomly the question arises as to whether its DoSomething method ends.

To fix this, you will need await for each Task value created.

 if (this.OnSomething != null) { foreach (var d in this.OnSomething.GetInvocationList().Cast<SomeEventHandler>()) { await d(args); } ] 
+10
source

All Articles