使用多線程的幾種方式示例詳解?
多線程使用的主要的幾種形式:
1)使用Thread類創(chuàng)建一個新線程
static void Main(string[] args){ Thread thread = new Thread(delegate(){ for (int i = 0; i <= 10; i++){ Console.WriteLine(Thread.CurrentThread.Name + ":" + i); Thread.Sleep(100); } }); thread.Name = "t1 thread"; thread.Start(); Console.WriteLine("TO DO SOMETHING..."); Console.ReadKey(true);}
2)使用async與await關(guān)鍵字配合使用
static void Main(string[] args){ Console.WriteLine("Main method start..."); Foo(); Console.WriteLine("TO DO SOMETHING..."); Console.WriteLine("Main method end..."); Console.ReadKey(true);} async static void Foo(){ Console.WriteLine("Foo method start."); await Task.Delay(2000); Console.WriteLine("Foo method end.");}
3)使用委托內(nèi)置的實例方法BeginInvoke實現(xiàn)異步編程
static void Main(string[] args){ Func<int, int, int> sum = (x, y) =>{ Thread.Sleep(2000); return x + y; }; sum.BeginInvoke(10, 5,(IAsyncResult asyncResult)=> { Console.WriteLine("callback method."); }, null); Console.WriteLine("TO DO SOMETHING..."); Console.ReadKey(true);}