日期:2014-05-17  浏览次数:20826 次

C#(同步调用、异步调用、异步回调)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace ConsoleApplication1
{
    public delegate int AddHandler(int a, int b);
    public class AddMethod
    {
        public static int Add(int a, int b)
        {
            Console.WriteLine("开始计算:" + a + "+" + b);
            Thread.Sleep(3000); //模拟该方法运行三秒
            Console.WriteLine("计算完成!");
            return a + b;
        }
    }
    
        
    //**************同步调用***********
    //委托的Invoke方法用来进行同步调用。同步调用也可以叫阻塞调用,它将阻塞当前线程,然后执行调用,调用完毕后再继续向下进行。

    //**************异步调用***********
    //异步调用不阻塞线程,而是把调用塞到线程池中,程序主线程或UI线程可以继续执行。
    //委托的异步调用通过BeginInvoke和EndInvoke来实现。

    //**************异步回调***********
    //用回调函数,当调用结束时会自动调用回调函数,解决了为等待调用结果,而让线程依旧被阻塞的局面。

    //注意: BeginInvoke和EndInvoke必须成对调用.即使不需要返回值,但EndInvoke还是必须调用,否则可能会造成内存泄漏。
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("===== 同步调用 SyncInvokeTest =====");
            AddHandler handler = new AddHandler(AddMethod.Add);
            int result=handler.Invoke(1,2);
            Console.WriteLine("继续做别的事情。。。");

            Console.WriteLine(result);
            Console.ReadKey();


            Console.WriteLine("===== 异步调用 AsyncInvokeTest =====");
            AddHandler handler1 = new AddHandler(AddMethod.Add);
            IAsyncResult result1=handler1.BeginInvoke(1,2,null,null);
            Console.WriteLine("继续做别的事情。。。");

            //异步操作返回
            Console.WriteLine(handler1.EndInvoke(result1));
            Console.ReadKey();

            Console.WriteLine("===== 异步回调 AsyncInvokeTest =====");
            AddHandler handler2 = new AddHandler(AddMethod.Add);
            IAsyncResult result2 = handler2.BeginInvoke(1, 2, new AsyncCallback(Callback), null);
            Console.WriteLine("继续做别的事情。。。");
            Console.ReadKey();


            //异步委托,也可以参考如下写法:
            //Action<object> action=(obj)=>method(obj);
            //action.BeginInvoke(obj,ar=>action.EndInvoke(ar),null);
            //简简单单两句话就可以完成一部操作。
        }
        static void Callback(IAsyncResult result)
        {
            AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
            Console.WriteLine(handler.EndInvoke(result));
        }
    }
}