码迷,mamicode.com
首页 > 其他好文 > 详细

基于委托的异步回调

时间:2016-09-17 10:37:10      阅读:109      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!