Aleksandar Toplek
Aleksandar Toplek

Reputation: 2831

Await on event handler

So here's deleagte and event

public delegate Task SomeEventHandler(SomeEventArgs e);

...


public event SomeEventHandler OnSomething;

Subscribers (multiple)

some.OnSomething += DoSomething;

...

public async Task DoSomething(SomeEventArgs e) {
    await SomethingElse();
    e.A = true;
}

Event call

if (this.OnSomething != null)
    await this.OnSomething(args);

// Here args.A is false
// It should be true

The problem is that last part continues even when DoSomething isn't finished. What would be the problem?

Upvotes: 10

Views: 5023

Answers (1)

JaredPar
JaredPar

Reputation: 755387

The problem here is that multiple instances of SomeEventHandler are running hence there are multiple Task values being created. The await call is only running on one of them hence it's somewhat up to chance as to whether or not it's theDoSomething method that ends up being awaited.

To fix this you will need to await on every Task value that is created

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

Upvotes: 12

Related Questions