【发布时间】:2020-08-17 08:08:47
【问题描述】:
所以我有一个方法从另一个类调用方法,并在调用另一个方法之前等待它们完成。我遇到的问题是被调用的方法使用事件处理程序来执行操作。有没有办法延迟该方法的返回,直到事件处理程序完成它的事情?为了澄清,我举了一个例子:
主类:
class MainClass
{
SomeObject someObject;
private async void MainMethod()
{
someObject = new SomeObject();
await someObject.SomeMethod();
await someObject.SomeOtherMethod();
}
}
SomeObject 类:
class SomeObject
{
public event EventHandler<object> SomethingChanged;
public async Task SomeMethod()
{
Console.WriteLine("fired SomeMethod");
SomethingChanged += SomethingChangedAsync;
Subscribe("<someURL>", SomethingChanged); //this is being done by an api im using...
await api.someApiCall;
Console.WriteLine("here things are happening that would make the event trigger. the method however, is now done with its logic and now returns and instantly goes to SomeOtherMethod but SomethingChangedAsync is not done processing what needs to be done");
}
public async Task SomeOtherMethod()
{
await api.someApiCall;
Console.WriteLine("fired SomeOtherMethod");
}
private async void SomethingChangedAsync(object sender, object e)
{
await api.someApiCall;
Console.WriteLine("doing stuff here that takes some time. i would like SomeMethod to wait with returning until the logic here is finished");
}
}
有什么办法可以解决这个问题。也许我的方法是完全错误的。我希望有人能帮我解决这个问题
【问题讨论】:
-
你有很多异步方法声明,但我没有在这些方法的实现中看到 await 关键字。
-
在您的示例中大量滥用 async 关键字。
-
@Hardood 我的错。在实际程序中的这些方法中有等待调用,但我没有将它们包括在这里。生病更新问题
-
如果这是真正的代码会更容易。有很多奇怪的事情正在发生。如果
MainMethod应该等到SomethingChanged事件被触发,那么为什么不让MainMethod订阅该事件并在事件处理程序中调用SomeOtherMethod()? -
有点复杂。看看这个:How do I await events in C#?
标签: c# multithreading events event-handling task