可以使用异步方法来执行委托,beginInvoke,endInvoke
用异步自己开辟线程,可能会造成线程阻塞(出现了程序不运行状态,应该是线程阻塞)
OBJECT类型用于传递任何想要的数据类型,它可以通过IAsyncResult的AsyncState属性获得。
注意事项:
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 }
时间: 2024-11-05 08:20:42