Include an event in an asynchronous / blocking call on Windows Phone 7 (C #)

(I asked this question earlier, but forgot to mention some limitations. This is for Windows Phone 7.1 (Mango) with Silverlight 4 and C # 4, which lacks System.Threading.Tasks , await , etc. I ask again about my native solution without third-party libraries like this .)

I wrap the library for my own use. To get a certain property, I need to wait for an event that works very quickly. I am trying to include this in a blocking call.

Basically, I want to turn

 void Prepare() { foo = new Foo(); foo.Initialized += OnFooInit; foo.Start(); } string Bar { return foo.Bar; // Only available after OnFooInit has been called. } 

In that

 string GetBarWithWait() { foo = new Foo(); foo.Initialized += OnFooInit; foo.Start(); // Wait for OnFooInit to be called and run, but don't know how return foo.Bar; } 

How could this be achieved?

+1
c # windows-phone-7 silverlight
source share
1 answer

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; } 
+1
source share

All Articles