泛型委托 Func<in T, out TResult>
http://www.cnblogs.com/jackson0714/p/5125808.html



1 class Program 2 { 3 //http://www.cnblogs.com/jackson0714/p/5125808.html 4 static void Main(string[] args) 5 { 6 Func<int, int> addDelegate = Add; 7 Console.WriteLine("Starting Main function ---------------"); 8 Thread.CurrentThread.Name = "Main Thread"; 9 string message = "I'm here!"; 10 addDelegate.BeginInvoke(2, AddCallback, message); 11 for (int i = 1; i < 4; i++) 12 { 13 Thread.Sleep(TimeSpan.FromSeconds(1)); 14 Console.WriteLine(" {0} started {1} second(s)", Thread.CurrentThread.Name, i); 15 } 16 Console.WriteLine("Read key ----------------------------"); 17 Console.ReadKey(); 18 } 19 private static void AddCallback(IAsyncResult ar) 20 { 21 string message = (string)ar.AsyncState;//输入状态 22 AsyncResult result = (AsyncResult)ar;//结果 23 Func<int, int> myDelegate = (Func<int, int>)result.AsyncDelegate; //异步调用的委托对象(addDelegate) 24 int sum = myDelegate.EndInvoke(ar); //结果返回 (从异步调用的委托对象中获取返回值) 25 Console.WriteLine("Add方法执行的结果:{0}",sum); 26 } 27 private static int Add(int num) 28 { 29 //判断当前线程是不是线程池线程 30 if (Thread.CurrentThread.IsThreadPoolThread) 31 { 32 //设置当前线程的名字为为 Pool Thread 33 Thread.CurrentThread.Name = "Pool Thread"; 34 } 35 Console.WriteLine(" Starting Add function ---------------"); 36 int sum = 0; 37 for (int i = 1; i < num + 1; i++) 38 { 39 sum += i; 40 Thread.Sleep(TimeSpan.FromSeconds(1)); 41 Console.WriteLine(" {0} started {1} second(s)", Thread.CurrentThread.Name, i); 42 } 43 Console.WriteLine(" End Add function -------"); 44 return sum; 45 } 46 }
浙公网安备 33010602011771号