You can do something like this:
string GetBarWithWait() { foo = new Foo(); using (var mutex = new ManualResetEvent(false)) { foo.Initialized += (sender, e) => { try { OnFooInit(sender, e); } finally { mutex.Set(); } } foo.Start(); mutex.WaitOne(); } return foo.Bar; }
But you must be absolutely sure that Foo will call the Initialized event no matter what happens. Otherwise, you will block the thread forever. If Foo has some kind of error event handler, subscribe to it to avoid blocking the stream:
string GetBarWithWait() { foo = new Foo(); using (var mutex = new ManualResetEvent(false)) { foo.Error += (sender, e) => { // Whatever you want to do when an error happens // Then unblock the thread mutex.Set(); } foo.Initialized += (sender, e) => { try { OnFooInit(sender, e); } finally { mutex.Set(); } } foo.Start(); mutex.WaitOne(); } return foo.Bar; }
Kevin gosse
source share