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

异步委托(APM)使用Func异步操作,处理耗时操作

时间:2016-07-11 23:42:46      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

使用委托进行异步操作,处理一些耗时操作,防止主线程阻塞

使用例子:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Demo
 7 {
 8     class Program
 9     {
10 
11         static void Main(string[] args)
12         {
13             Func<string> fun = new Func<string>(Test);   
14             Console.WriteLine("异步执行开始(异步委托的方法):" + fun.Method);
15            IAsyncResult asyncResult= fun.BeginInvoke(CallBack,new string []{"sadha","sahsiuh"});  //开始异步操作
16 
17             for (int i = 0; i < 10;i++ )
18             {
19                 Console.WriteLine("异步方法执行时同时执行其它代码:"+i);
20             }
21 
22             fun.EndInvoke(asyncResult);  //结束异步
23             Console.ReadKey();
24         }
25 
26         /// <summary>
27         /// 异步执行的方法
28         /// </summary>
29         /// <returns></returns>
30         public static string Test()
31         {
32             return DateTime.Now.ToString();
33         }
34 
35         /// <summary>
36         /// 异步方法执行完成回掉的方法
37         /// </summary>
38         /// <param name="async"></param>
39         public static void CallBack(IAsyncResult async)
40         {
41             string [] array= async.AsyncState as string [];
42             Console.WriteLine("异步操作是否完成:"+ async.IsCompleted);
43         }
44     }
45 }

上述代码运行结果:

技术分享

异步委托(APM)使用Func异步操作,处理耗时操作

标签:

原文地址:http://www.cnblogs.com/linJie1930906722/p/5661944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!