这是一个C#问题 我想对异步事件回调进行同步调用。 请参阅代码中的注释
class User
{
EventHandler Service1Started()
{
"Looks like service 1 started as I got event from server class" ;
}
EventHandler Service2Started()
{
"Looks like service 2 started as I got event from server class" ;
}
public void StartServicesOnlyStartService2AfterService1Started()
{
Server server = new Server();
// want to call these 2 methods synchronously here
// how to wait till service1 has started thru the event we get
// Want to avoid polling, sleeping etc if possible
server.StartService1();
server.StartService2();
}
}
答案 0 :(得分:3)
您的代码非常不清楚,但最简单的方法就是为Service1启动服务2的事件处理程序:
server.Service1Started += delegate { server.StartService2(); };
答案 1 :(得分:2)
Jon的答案是对的,如果使用delegate
不方便,这是等效的:
EventHandler Service1Started()
{
// Looks like service 1 started as I got event from server class
server.StartService2();
}