首页 > 其他 > 详细

基于委托的异步回调

时间:2016-09-17 10:34:02      阅读:125      评论:0      收藏:0      [点我收藏+]

 异步回调时在调用 BeginInvoke时提供的回调方法,主线程就不必再等待异步线程工作完毕,异步线程在工作结束后会主动调用提供的回调方法。

    class Program

    {

        public delegate void PrintDelegate(string content);

        static void Main(string[] args)

        {

            int threadId = Thread.CurrentThread.ManagedThreadId;

            PrintDelegate printDelegate = new PrintDelegate(Print);

 

            Console.WriteLine("[主线程id:{0}]\t开始调用打印的方法...", threadId);

            IAsyncResult result = printDelegate.BeginInvoke("Hello Word!", PrintComplete,printDelegate);

            Thread.Sleep(1000);

            Console.ReadLine();

 

        }

 

        public static void Print(string content)

        {

            int threadId = Thread.CurrentThread.ManagedThreadId;

            Console.WriteLine("[当前线程id:{0}]\t{1}",threadId,content);

            Thread.Sleep(1000);

        }

 

        private static void PrintComplete(IAsyncResult asyResult)

        {

            if (null == asyResult)

            {

                throw new ArgumentException();

            }

            int threadId = Thread.CurrentThread.ManagedThreadId;

 

            (asyResult.AsyncState as PrintDelegate).EndInvoke(asyResult);

            Console.WriteLine("[当前线程id:{0}]\t打印方法调用完毕。", threadId);

        }

    }

基于委托的异步回调

原文:http://www.cnblogs.com/lx4556332/p/5878040.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!