多執行緒使用的主要的幾種形式:
1)使用Thread類建立一個新執行緒
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關鍵字配合使用
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)使用委託內建的例項方法BeginInvoke實現非同步程式設計
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);}
多執行緒使用的主要的幾種形式:
1)使用Thread類建立一個新執行緒
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關鍵字配合使用
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)使用委託內建的例項方法BeginInvoke實現非同步程式設計
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);}