04委托开启线程

Func<先写完参数,再写返回值>

1.异步委托的方式 : 这个里的是等待结束

Thread.Sleep(10),睡眠10毫秒

 

if里的判断是???不用等待,一直检查是否为真

2.等待句柄的方式:这个里的是等待过程

if里发判断是阻止线程运行时间.b为true表示等待完成,你的结果有没有完成我都要离开了,有我就带着答案走,

睡眠200毫秒,等待250毫秒

 

 

 

 1 //2018/09/26 17:27:23
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading;
 7 using System.Threading.Tasks;
 8 
 9 namespace _004委托开启线程
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Func<int, string, int> f = Text;
16             // f.BeginInvoke(20,"abc",null,null);//开启一个线程
17             IAsyncResult ar = f.BeginInvoke(20, "abc", null, null);//返回当前异步委托状态,持续进行,直到拿到返回值
18             //while (!ar.IsCompleted) //看一下等待的过程
19             //{
20             //    Console.WriteLine("*");
21             //    Thread.Sleep(10);
22             //}
23             int resoult = f.EndInvoke(ar);
24             Console.WriteLine("Main");
25             Console.WriteLine(resoult);

//第二种开启方式等待句柄异步委托
26 //Func<int, string, int> f = Text; 27 //IAsyncResult ar = f.BeginInvoke(20, "张三", null, null); 28 //bool b = ar.AsyncWaitHandle.WaitOne(50);//返回阻止线程运行时间,b为true表示结果等待完成(最多等待的时间) 29 //if (b) 30 //{ 31 // int resoult = f.EndInvoke(ar); 32 // Console.WriteLine(resoult); 33 //} 34 35 } 36 public static int Text(int age, string name) 37 { 38 39 Thread.Sleep(20); 40 Console.WriteLine(age + name); 41 return 100; 42 } 43 } 44 }

 3.第三种开启方式 匿名委托回调函

(题外 匿名委托的用法)

 

3.用匿名委托的方式完成和上边一样的操作

 

 

 1  Func<int, string, int> f = Text;
 2             //  f.BeginInvoke(20, "张三", BackObject, f);
 3             Func<int, string, int> f = Text;
 4             f.BeginInvoke(20, "张三", ar =>
 5             {
 6                 int res = f.EndInvoke(ar);
 7                 Console.WriteLine(res);
 8             }, f);
 9             Console.ReadKey();
10         }
11         public static void BackObject(IAsyncResult ar)
12         {
13             Func<int, string, int> f = ar.AsyncState as Func<int, string, int>;
14             int res = f.EndInvoke(ar);
15             Console.WriteLine(res);
16 
17 
18         }

 

posted @ 2018-09-26 18:56  白纸菇凉  阅读(155)  评论(0编辑  收藏  举报