委托的异步调用示例(1)

2008-06-29 20:18

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace 委托的异步调用
{
    public delegate void DelegateClass();//定义委托分类DelegateClass
    class Starter
    {
        static void Main(string[] args)
        {
            DelegateClass del = MethodA;//定义委托对象del
            DelageteStateBag state = new DelageteStateBag();//状态值state
            IAsyncResult ar = del.BeginInvoke(Callback, state);// 开始委托的异步调用
           
            if (ar.IsCompleted == true)
                Console.WriteLine("MethodA completed");
            else
                Console.WriteLine("MethodA not completed");
            ar.AsyncWaitHandle.WaitOne();

            Thread.Sleep(100);
            lock(state)
            {
                Console.WriteLine("Back in Main");
                Console.WriteLine(state.message);

            }
        }
        /// <summary>
        /// 完成异步委托时的调用方法
        /// </summary>
        /// <param name="ar"></param>
        public static void Callback(IAsyncResult ar)
        {
            DelageteStateBag state = (DelageteStateBag)ar.AsyncState;
            lock (state)
            {
                Console.WriteLine("Callback Running");
                ((DelageteStateBag)ar.AsyncState).message = "state object modified in callback.";
            }
        }
        public static void MethodA()
        {
            Console.WriteLine("MethodA running ....");
            Thread.Sleep(200);
        }
     }
    class DelageteStateBag
    {
        public string message;
    }
}
//注:Main()方法末尾有一个thread.sleep()语句,该语句如果被删除,在Main()和CallBack()
//例程间会存在竞争。因为 ar.AsyncWaitHandle.WaitOne()语句产生阻塞,当MethodA()执行完成时,阻塞消失 ,
//Main()和CallBack()都将继续,竞争开始。Main()Sleep()之后,允许CallBack()允许为共享的state对象加锁。

posted @ 2010-02-03 09:36  玄魂  阅读(302)  评论(0编辑  收藏  举报