可使用異步方法來執行委託,beginInvoke,endInvoke
用異步本身開闢線程,可能會形成線程阻塞(出現了程序不運行狀態,應該是線程阻塞)
OBJECT類型用於傳遞任何想要的數據類型,它能夠經過IAsyncResult的AsyncState屬性得到。異步
注意事項:async
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.Remoting.Messaging; 5 using System.Text; 6 using System.Threading; 7 using System.Threading.Tasks; 8 9 namespace ConsoleTest 10 { 11 class AsyncDelegate 12 { 13 public delegate int Adddelegate(int x, int y); 14 static void Main(string[] args) 15 { 16 TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks); //獲取當前時間的刻度數 17 System.Console.WriteLine("線程開始了begintime:{0}-------------------\r\n",System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss ffff")); 18 Thread.CurrentThread.Name = "Main Thread"; 19 AsyncDelegate ad = new AsyncDelegate(); 20 //int sd = ad.Add(4, 5); 21 Adddelegate adl = new Adddelegate(ad.Add); 22 // IAsyncResult asyncResult = adl.BeginInvoke(7, 8, null, null); 23 AsyncCallback asynccll = new AsyncCallback(ad.AsyncAdd);//AsyncCallback其實也是一種委託,接受的參數爲簽名(IAsyncCallback ar) 24 Object ob = (object)"我是傳遞的數據"; 25 adl.BeginInvoke(4,6, asynccll,ob); 26 27 for (int i = 0; i < 5; i++) 28 { 29 Thread.Sleep(TimeSpan.FromSeconds(i)); 30 System.Console.WriteLine("線程名:{0},等待時間{1}", Thread.CurrentThread.Name, i); 31 } 32 // int sd = adl.EndInvoke(asyncResult); 33 System.Console.WriteLine("\n想退出按任意鍵!!!"); 34 // System.Console.WriteLine("返回值是{0}", sd); 35 TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks); 36 TimeSpan ts = ts2.Subtract(ts1).Duration(); //時間差的絕對值 37 String spanTime = ts.Hours.ToString() + "小時" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒"; //以X小時X分X秒的格式現實執行時間 38 System.Console.WriteLine("線程開始了endtime:{0}-----\r\n{1}", System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss ffff"),spanTime); 39 40 } 41 public int Add(int x, int y) 42 { 43 if (Thread.CurrentThread.IsThreadPoolThread) 44 { 45 //給開闢的線程池中的子線程設置名稱 46 Thread.CurrentThread.Name = "HAHHA"; 47 } 48 System.Console.WriteLine("方法開始了"); 49 for (int i = 0; i <= 2; i++) 50 { 51 Thread.Sleep(TimeSpan.FromSeconds(i)); 52 System.Console.WriteLine("線程名:{0},等待時間{1}", Thread.CurrentThread.Name, i); 53 } 54 System.Console.WriteLine("方法執行完畢"); 55 return x + y; 56 } 57 public void AsyncAdd(IAsyncResult ar) 58 { 59 AsyncResult acresult = (AsyncResult)ar; 60 Adddelegate del = (Adddelegate)acresult.AsyncDelegate; 61 string data = acresult.AsyncState.ToString(); 62 int stn = del.EndInvoke(acresult); 63 System.Console.WriteLine("線程名稱:{0},返回值:{1},傳遞的數據{2}",Thread.CurrentThread.Name,stn,data); 64 65 } 66 } 67 }