How to cause asynchronous operation as synchronization?

I have a third-party service that has the operation async DoAsync () and Done (). How can I create my own DoSync () synchronization? I want something like this (in pseudocode):

operation DoSync() { DoAsync(); wait until Done(); } 
0
asynchronous events
source share
2 answers

One way to do this is to temporarily add an event handler, and in this handler, set some kind of expected object. Here is an example that shows a technique with one of the async methods provided by WebClient

 using System; using System.Net; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { WebClient w = new WebClient(); using (var waiter = new ManualResetEventSlim()) { DownloadDataCompletedEventHandler h = (sender, e) => { if (e.Error != null) { Console.WriteLine(e.Error); } waiter.Set(); }; w.DownloadDataCompleted += h; try { w.DownloadDataAsync(new Uri("http://www.interact-sw.co.uk/iangblog/")); Console.WriteLine("Downloading"); waiter.Wait(); Console.WriteLine("Finished!"); } finally { w.DownloadDataCompleted -= h; } } } } } 

Here's a simplified version that makes it easier to view the basic technique, but that doesn't bother with things like error handling or cleaning up after yourself:

 WebClient w = new WebClient(); using (var waiter = new ManualResetEventSlim()) { w.DownloadDataCompleted += delegate { waiter.Set(); }; w.DownloadDataAsync(new Uri("http://www.interact-sw.co.uk/iangblog/")); Console.WriteLine("Downloading"); waiter.Wait(); Console.WriteLine("Finished!"); } 

In most situations, you will need to make sure that you find errors and detach the handler when you're done - I just provided a shorter version to help illustrate this point. I would not use this simplified one in a real program.

+1
source share
+2
source share

All Articles