zoukankan      html  css  js  c++  java
  • 【原创】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();

  • 相关阅读:
    eclipse连接远程hadoop集群开发时0700问题解决方案
    螺旋线
    双曲抛物面
    双曲抛物面
    工业相机标定相关知识整理
    高科技 stuff
    高科技 stuff
    杜甫诗百首
    杜甫诗百首
    经典纪录片
  • 原文地址:https://www.cnblogs.com/zhxhdean/p/2349594.html
Copyright © 2011-2022 走看看