
在C#中,有几种方式可以使用多线程。
一种是使用Thread类,可以创建和控制线程的生命周期。
另一种是使用ThreadPool类,它提供了一个线程池,可以重用线程来执行任务。还可以使用Task类和async/await关键字,它们提供了一种更高级的方式来处理异步操作。
此外,还可以使用Parallel类来执行并行操作,它可以自动将任务分配给多个线程。无论使用哪种方式,都需要注意线程安全和同步问题,以避免竞态条件和死锁等问题。
多线程使用的主要的几种形式:
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);}