多线程使用的主要的几种形式:
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);}
温馨提示:内容为网友见解,仅供参考