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

旧时模样 提交于 2020-01-24 00:38:26
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对象加锁。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!