C# 异步委托使用

static void Main(string[] args)
   {
       // 创建委托并注册方法
       TakesAWhileDelegate dl = TakesAWhile;
       // 创建异步结果,执行委托
       IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null);
       // 判断是否执行完成
       while (!ar.IsCompleted)
       {
           Console.Write(".");
           Thread.Sleep(50);
       }
       // 执行完后获得结果
       int result = dl.EndInvoke(ar);
       Console.WriteLine("result: {0}", result);
       Console.ReadKey();
   }

   // 委托变量
   public delegate int TakesAWhileDelegate(int data, int ms);

   // 方法体
   static int TakesAWhile(int data, int ms)
   {
       Console.WriteLine("TakesAWhile started");
       Thread.Sleep(ms);
       Console.WriteLine("TakesAWhile completed");
       return ++data;
   }
发布了84 篇原创文章 · 获赞 77 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/lujiachun1/article/details/78739367