04委托开启线程
Func<先寫完參數,再寫返回值>
1.異步委托的方式 : 這個里的是等待結束
Thread.Sleep(10),睡眠10毫秒
?
if里的判斷是???不用等待,一直檢查是否為真
2.等待句柄的方式:這個里的是等待過程
if里發(fā)判斷是阻止線程運行時間.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);//返回當前異步委托狀態(tài),持續(xù)進行,直到拿到返回值 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 }?
轉載于:https://www.cnblogs.com/satanj/p/9708902.html
總結
- 上一篇: a标签加入单击事件 屏蔽href跳转页面
- 下一篇: MyBatis的运行的核心原理解析(三)