如何调用异步操作同步? [英] How to invoke async operation as sync?

查看:111
本文介绍了如何调用异步操作同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有异步DoAsync()操作和Done()事件第三方服务。如何创建我自己的同步DoSync()操作?
我想水木清华这样的(伪code):

 操作DoSync()
{
    DoAsync();
    等到完成();
}


解决方案

要做到这一点是临时添加事件处理程序,并且在处理器的一种方式,设置某种可等待的对象。下面是显示了由 Web客户端

提供异步方法之一,该技术的例子

 使用系统;
使用System.Net;
使用的System.Threading;命名空间的ConsoleApplication1
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            WebClient的W =新的WebClient();            使用(VAR服务员=新ManualResetEventSlim())
            {
                DownloadDataCompletedEventHandler H =(发件人,E)=>
                {
                    如果(e.Error!= NULL)
                    {
                        Console.WriteLine(e.Error);
                    }
                    waiter.Set();
                };                w.DownloadDataCompleted + = H;
                尝试
                {
                    w.DownloadDataAsync(新的URI(http://www.interact-sw.co.uk/iangblog/));
                    Console.WriteLine(下载);
                    waiter.Wait();
                    Console.WriteLine(完了!);
                }
                最后
                {
                    w.DownloadDataCompleted - = H;
                }
            }
        }
    }
}

下面是一个简化版本,使基本技术更容易看到,但不喜欢的事情错误处理怕麻烦,或本身后整理:

  WebClient的W =新的WebClient();使用(VAR服务员=新ManualResetEventSlim())
{
    w.DownloadDataCompleted + = {委托waiter.Set(); };
    w.DownloadDataAsync(新的URI(http://www.interact-sw.co.uk/iangblog/));
    Console.WriteLine(下载);
    waiter.Wait();
    Console.WriteLine(完了!);
}

在你将要确保你发现错误,取下处理器时,即可大功告成大多数情况下 - 我只是提供了较短的版本,以帮助说明这一点。我不会实际使用在一个真实的程序,简化之一。

I have a third party service which have async DoAsync() operation and Done() event. How can I create my own sync DoSync() operation? I want smth like this (in pseudocode):

operation DoSync()
{
    DoAsync();
    wait until Done();
}

解决方案

One way to do this is to temporarily add an event handler, and in that handler, set some sort of waitable object. Here's an example that shows the 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 the basic technique easier to see, but which doesn't bother with things like error handling, or tidying up after itself:

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 want to make sure you detect errors, and detach the handler when you're done - I just provided the shorter version to help illustrate the point. I wouldn't actually use that simplified one in a real program.

这篇关于如何调用异步操作同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆