| William さんのプロフィール.Net Zoneブログリスト | ヘルプ |
|
9月7日 Wait for async completion using two locks instead of an event.
Sometimes you need to wait (or block) for an async method to complete. This could be The key is to use two locks. The first is just an exclusive lock to keep other callers blocked. The second object syncRoot = new object(); object exclusiveLock = new object(); //... lock (exclusiveLock) lock (syncRoot) { // Kick off async here and pulse syncRoot to free thread when complete.new Thread( delegate() {Console.WriteLine("Inside async routine."); Thread.Sleep(1000);lock (syncRoot) // Need to own lock before pulse. {Monitor.Pulse(syncRoot); // Pulse Waiting thread. } Console.WriteLine("Pulsed syncroot."); }).Start(); // Wait for async callback to complete. Monitor.Wait(syncRoot); } // Exit both locks. |
|
|