C# 代理的异步特性(Asynchronous Nature of Delegates)

http://www.penna.cn/blog/?p=127

 

  

 

 

 

原文:http://www.c-sharpcorner.com/UploadFile/Ashush/AsyncDelegates03032008144119PM/AsyncDelegates.aspx

作者:Amr Ashush

翻译:Penna

本文介绍了如何利用代理类型来实现异步调用,向您展示代理类型的另一面。

引言

.Net中构建多线程应用程序有以下几种方法:

1、使用代理(delegates)进行异步调用

2、使用BackgroundWorker组件

3、使用Thread

本文只涉及异步代理调用,如果您想了解另外两种方法,请参阅作者的相关文章:

Using the BackgroundWorker component

Building a multithreaded application using Thread calss

这里假设您已经足够了解代理类型,否则,请移步:

Delegates in C#

异步代理调用(Asynchronous delegates calls

先来看看一般的代理调用,在应用程序中通过代理来指向一个方法,供后面调用:

示例 1:

namespace DelegateSynchronousCalls
{
    public delegate int MyDelegate(int x);
    public class MyClass
    {
        //A method to be invoke by the delegate
        public int MyMethod(int x)
        {
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //invoke the method synchronously

            int result = del(5);
            //this text will not show till the first operation finish
            Console.WriteLine("Proccessing operation…");
            Console.WriteLine("Result is: {0}", result);
            Console.ReadLine();
        }
    }
}

您可以看到,我们在main线程中使用代理(del)来调用 一个方法(myClass1.MyMethod),如果这个方法是一个较长的进程,例如:

public int MyMethod(int x)
{
    //simulate a long running proccess
    Thread.Sleep(10000);
    return x*x;   
}

这个操作将会持续十秒钟,在这个过程中整个程序将没有响应,并且不能进行其他操作,只能等待这个方法调用结束。

那么如何解决这个问题呢?呵呵,自然是使用代理进行异步调用了 ,如何实现?请看下面的例子:

示例2

namespace
DelegatesAsynchronousCalls

{
    class Program

    {
        public delegate int MyDelegate(int x);

        public class MyClass
        {
            //A method to be invoke by the delegate
            public int MyMethod(int x)
           {
                //simulate a long running proccess
                Thread.Sleep(10000);
                return x * x;
            }
        }

        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our method in another thread
            IAsyncResult async = del.BeginInvoke(5, null, null);

            //do something while MyMethod is executing.

            Console.WriteLine("Proccessing operation…");

            //recieve the results.
            int result = del.EndInvoke(async);
            Console.WriteLine("Result is: {0}", result);
            Console.ReadLine();
        }
    }
}

  您可以看到,我们像往常一样定了一个代理,但却没有直接通过它来调用方法,而是调用代理的BeginInvoke()方法,该方法返回一个IAsyncResult对象,然后把这个对象提交给代理的EndInvoke()方法,最终由EndInvoke()来提供返回值。(复杂吧!!??)『译者注:还好 

  这时您会问,这些方法都是哪来的?答案很简单,当您定义一个代理时,一个特定的(custom)代理类将生成并添加到你的程序集当中。这个类包含很多方法,像Invoke(),BeginInvoke()EndInvoke()

>等。当您使用代理调用一个方法是,实际上是调用了代理类的Invoke()方法,Invoke()方法在主线程中同步执行你指定的方法,如示例1。而异步调用某一方法(underlying method)时,您首先调用BeginInvoke(),此时您的方法将被加入另一线程的队列中等待执行。 BeginInvoke()并不返回您指定方法的返回值,而是返回一个IAsyncResult对象,可在异步操作完成时访问它。要获得执行结果,把IAsyncResult传给代理的EndInvoke()方法, EndInvoke()等待异步操作完成,然后返回执行结果。

  您可能会问,BeginInvoke()方法的另外两个参数是干啥的?另外两个参数,第一个是用来传递回调方法(callback),另一个是一个状态对象。若您不需要这些选项,只要传空值(null)就可以了。下面来看看如何使用它们。

使用AsyncCallback delegate

  让调用进程知道异步操作是否已经完成,可以有两种方式,第一个是使用IAsyncResult接口的IsCompleted属性。在调用EndInvoke()之前,调用线程可以通过这个属性来判断异步操作是否完成,若未完成IsCompleted返回false。若IsComplete返回true,调用线程就可以获取结果了。

示例 3

namespace
DelegatesAsyncCallsIsCompleted

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {
        //A method to be invoke by the delegate

        public int MyMethod(int x)
        {
            //simulate a long running proccess
            Thread.Sleep(3000);
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread
            IAsyncResult async = del.BeginInvoke(5, null, null);

            //loop until the method is complete
            while (!async.IsCompleted)
            {
                Console.WriteLine("Not Completed");
            }

            int result = del.EndInvoke(async);
            Console.WriteLine("Result is: {0}", result);
            Console.ReadLine();

        }
    }

}


如果用一个代理来告知调用进程异步操作已经完成,效果会更好。为此,您必须向BeginInvoke()方法提供一个AsyncCallback代理的实例作为参数,这个代理会在异步操作完成时自动调用指定的方法。
这个指定的方法必须含有一个唯一的IAsyncResult类型的参数,并且没有返回值(返回void)。

public
static void MyCallBack(IAsyncResult async)

{

}

这个IAsyncResult对象和您调用BeginInvoke() 方法是返回的是同一个对象。

示例4

namespace
AsyncCallbackDelegate

{
    public delegate int MyDelegate(int x);
    public class MyClass
    {
        //A method to be invoke by the delegate
        public int MyMethod(int x)
        {
            //simulate a long running proccess
            Thread.Sleep(10000);
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread
            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), null);
            Console.WriteLine("Proccessing the Operation….");
            Console.ReadLine();
        }

        static void MyCallBack(IAsyncResult async)
        {
            Console.WriteLine("Operation Complete);
        }

    }
}

  记住,MyCallback()在MyMethod()方法完成时将由AsyncCallback调用。
  您可以看到,我们并没有调用EndInvoke(),因为MyCallback()方法没有访问MyDelegate对象,因此,我们可以将传入的IAsyncResult参数转换为AsyncResult类型,然后使用静态的AsyncDelegate属性来引用由其他地方生成的原始异步代理。

我们可以重写MyCallback()方法,如下所示:

static
void MyCallBack(IAsyncResult async)

{

    AsyncResult ar = (AsyncResult)async;

    MyDelegate del = (MyDelegate)ar.AsyncDelegate;

    int x = del.EndInvoke(async);

    Consol.WriteLine("Operation Complete, Result is: {0}", x);

}

BeginInvoke()方法的最后一个参数用来传递附加的状态信息给主线程的回调方法。这是参数是System.Object类型的,所以您可以传递任何类型的信息。

示例 5

namespace AsyncCallbackDelegate
{
    public delegate int MyDelegate(int x);
    public class MyClass
    {
        //A method to be invoke by the delegate
        public int MyMethod(int x)
        {
            //simulate a long running proccess
            Thread.Sleep(10000);
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread
            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), "A message from the main thread");
            Console.WriteLine("Proccessing the Operation….");
            Console.ReadLine();
        }

        static void MyCallBack(IAsyncResult async)
        {
            AsyncResult ar = (AsyncResult)async;
            MyDelegate del = (MyDelegate)ar.AsyncDelegate;
            int x = del.EndInvoke(async);
 
            //make use of the state object.
            string msg = (string)async.AsyncState;
            Console.WriteLine("{0}, Result is: {1}", msg, x);
        }
    }
}

希望本文对您理解代理的异步特性有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值