直接上代碼
1.BeginInvoke和EndInvoke方式
private static void BeginInvoke1() { Func<int,string> fun = Todo; for (int i = 0; i < 5; i++) { //fun.BeginInvoke(i,TodoCallBack, fun); /* 異步調用委托BeginInvoke * handler.EndInvoke(x)為執行委托的結果 */ fun.BeginInvoke(i, x => { Func<int, string> handler = x.AsyncState as Func<int, string>; //str:為異步調用的返回值 string str=handler.EndInvoke(x); Console.WriteLine(str); }, fun); } }
第二種Thread
private static void Test(object i) { Console.WriteLine(i.ToString()); } private static void Thread1() { //可以傳入一個object值,不能接收返回值 System.Threading.Thread t = new System.Threading.Thread(Test); t.Start(10); }
線程池的啟用
private static void ThreadPools() { System.Threading.ThreadPool.QueueUserWorkItem(x => { Console.WriteLine("線程池啟動"+x); },"ss"); }
第三種:Task,這個是在.net4.0以后才出來的
private static void TaskFac() { //工廠屬性的調用方式 Task t = Task.Factory.StartNew(x => { Console.WriteLine("測試"+x); },"taskFac"); }
//無參數下發
System.Threading.Tasks.Task.Factory.StartNew(()=>{
new PushWeiXin().RefundNotify(drawbackInfo.orderno,drawbackInfo.username, drawbackInfo.drawback_reason);
});
private static void TestTask() { //簡單的調用方式 Task t = new Task((x) => { System.Threading.Thread.Sleep(1000); Console.WriteLine("測試"+x); },"task"); t.Start(); //t.Wait();//讓主線程執行完成后執行后面的代碼 Console.WriteLine("主線程完成"); }