我有第三方服務有異步DoAsync()操作和完成()事件。我如何創建自己的同步DoSync()操作? 我想水木清華這樣的(僞代碼):如何調用異步操作作爲同步?
operation DoSync()
{
DoAsync();
wait until Done();
}
我有第三方服務有異步DoAsync()操作和完成()事件。我如何創建自己的同步DoSync()操作? 我想水木清華這樣的(僞代碼):如何調用異步操作作爲同步?
operation DoSync()
{
DoAsync();
wait until Done();
}
的一種方式做,這是臨時添加事件處理程序,並在處理程序中,設置某種可等待的對象。下面是顯示技術與由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;
}
}
}
}
}
下面是一個簡化版本,使基本技術更容易看清所提供的異步方法一個例子,但不與諸如錯誤處理,或整理打擾達後本身:
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!");
}
在你將要確保你發現錯誤,並卸下處理器時,即可大功告成大多數情況下 - 我只是提供了較短的版本,以幫助說明這一點。我實際上不會在真正的程序中使用這個簡化的程序。