如何调用异步操作作为同步?
问题描述:
我有第三方服务有异步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!");
}
在你将要确保你发现错误,并卸下处理器时,即可大功告成大多数情况下 - 我只是提供了较短的版本,以帮助说明这一点。我实际上不会在真正的程序中使用这个简化的程序。