【原创】C#异步调用

使用委托,异步调用方法(适用调用方法消耗时间比较长)

       delegate void ShowTime(int i);//定义委托

        delegate string ShowTime2(int i);
        //定义委托需要指向的方法,参数类型,个数,返回值对应委托
        private static void show(int i)
        {
            System.Threading.Thread.Sleep(5000);
            Console.WriteLine(i + ":" + DateTime.Now);//5秒后才会显示
        }

        private static string show2(int i)
        {
            System.Threading.Thread.Sleep(5000);
            return DateTime.Now.ToShortDateString(); //5秒后返回
        }
        static void Main(string[] args)
        {
            Console.WriteLine("主程序开始");
            Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);

            /*
             * ShowTime s = new ShowTime(show);
            s.BeginInvoke(1, null, null);//异步调用,无返回值,直接调用BeginInvoke就可以了。
            */

            /*
            //如果方法需要 返回值,则需调用EndInvoke
            ShowTime2 s = new ShowTime2(show2);
            IAsyncResult rlt = s.BeginInvoke(1, null, null);

            Console.WriteLine("主程序做其他事情");//立刻显示
            //判断show2是否已经完成
            while (!rlt.IsCompleted)
            {
                Console.WriteLine("show2方法正在处理中....");
                System.Threading.Thread.Sleep(1000);
            }
            string frlt = s.EndInvoke(rlt);
            Console.WriteLine(frlt);
             */           

            Console.ReadKey();

posted on 2012-02-13 16:19  BarneyZhang  阅读(183)  评论(0编辑  收藏  举报

导航