委托的异步调用示例(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对象加锁。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值