c#_delegate_异步调用_BeginInvoke

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

//异步调用
//IAsyncResult BeginInvoke(argument,AsyncCallback callback,object asynState)
//argument - 如果没有参数,callback就是第一个参数
//BeginInvoke返回值是IAsyncResult
//AsyncState - 传递给异步调用的那个状态对象
//AsyncWaitHandle - 在异步操作完成前,一直使用WaitHandle阻断调用线程
//CompleteSynchronously - 指示一步操作是否同步完成
//IsCompleted - 指示异步操作已经完成

namespace Starter
{
    public delegate void DeleageteClass();

    class Program
    {
        static void Main(string[] args)
        {
            DeleageteClass del = MethodA;

            DelegateStateBag state = new DelegateStateBag();

            IAsyncResult ar = del.BeginInvoke(Callback,state);

            if (ar.IsCompleted == true)
            {
                Console.WriteLine("MethodA completed");
            }
            else
            {
                Console.WriteLine("MethodA not completed");
            }
            
            ar.AsyncWaitHandle.WaitOne();

            //do something else
            
            //Sleep - 不然会产生竞争,同时启动Callback和main,Sleep是消除竞争的根本办法
            Thread.Sleep(100);

            lock (state)
            {
                Console.WriteLine("Back in main");
                Console.WriteLine(state.message);
            }

            Console.ReadLine();
        }

        public static void Callback(IAsyncResult ar)
        {
            DelegateStateBag state = (DelegateStateBag)ar.AsyncState ;
            lock(state)
            {
                Console.WriteLine("Call back running");
                ((DelegateStateBag)ar.AsyncState).message = 
                    "State object modify in callack";
            }

        }


        public static void MethodA()
        {
            Console.WriteLine("MethodA running....");
            Thread.Sleep(200);
        }
    }

    class DelegateStateBag
    {
       public string message;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值