philzhou

导航

使用 AsyncCallback 处理异步调用

参考文章 原文

        异步调用可以避免主线程受工作线程阻塞,即工作线程执行的过程中,主线程依然可以往下运行,不必等待工作线程完成。下面是一个简单的异步调用加法函数的例子。

using System;
using System.Threading;
// the namespace for AsyncResult.
using System.Runtime.Remoting.Messaging;

namespace AsyncCallback
{
    // Delegate for add method.
    public delegate int TwoOperands(int a,int b);

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main is running on thread " + Thread.CurrentThread.ManagedThreadId);
            TwoOperands operation = new TwoOperands(Add);
            //async calling the add.
            //new System.AsyncCallback(CallbackHandler) 回调处理函数, 异步调用结束后,runtime会调用该函数。
            // "Async parameter" 作为回调参数,传给回调函数,通过 AsyncResult.AsyncState 获取
            operation.BeginInvoke(2, 3, new System.AsyncCallback(CallbackHandler), "Async parameter");
            Console.WriteLine("Main is running on thread " + Thread.CurrentThread.ManagedThreadId);
            Console.Read();
        }

        /// <summary>
        /// 回调处理函数
        /// </summary>
        /// <param name="iar">回调参数</param>
        static void CallbackHandler(IAsyncResult iar)
        {
            Console.WriteLine("CallbackHandler is running on thread " + Thread.CurrentThread.ManagedThreadId);           
            AsyncResult ar = (AsyncResult)iar;
            // 获取原委托对象。
            TwoOperands operation = (TwoOperands)ar.AsyncDelegate;
            // 结束委托调用。
            int i = operation.EndInvoke(iar);
            // 打印异步调用传入的参数。
            Console.WriteLine("The Async calling parameter is " + ar.AsyncState);
            Console.WriteLine("The adding result is " + i);           
        }

        static int Add(int i, int j)
        {
            Console.WriteLine("Add is running on thread " + Thread.CurrentThread.ManagedThreadId + "...");
            Thread.Sleep(5000);
            return i + j;
        }
    }
}

输出结果

image

由此可见,异步调用的函数,与异步回调函数是在同一线程上运行的。

posted on 2011-02-23 14:39  philzhou  阅读(7520)  评论(1编辑  收藏  举报