等待事件处理程序事件、程序

2023-09-03 17:03:59 作者:倾城泪

因此​​,这里的deleagte和事件

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;
}

事件中调用

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

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

问题是,最后一部分继续即使DoSomething的还没有完成。会是什么问题?

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

推荐答案

这里的问题是, SomeEventHandler 正在运行的多个实例,因此有多个正在创建任务值。该等待通话只在其中的一个上运行,因此它有点最多的机会,因为关于是否它是的DoSomething 方法最终被期待已久的。

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);
  }
]