阅读量:0
在C#中,可以使用.NET Framework提供的多线程功能来创建和管理线程
- 使用Thread类:
using System; using System.Threading; class Program { static void Main() { Thread newThread = new Thread(new ThreadStart(MyMethod)); newThread.Start(); } static void MyMethod() { Console.WriteLine("This is a new thread."); } }
- 使用ThreadPool类:
using System; using System.Threading; class Program { static void Main() { ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod)); Console.ReadLine(); } static void MyMethod(object state) { Console.WriteLine("This is a thread from the thread pool."); } }
- 使用Task类(Task Parallel Library, TPL):
using System; using System.Threading.Tasks; class Program { static void Main() { Task task = Task.Factory.StartNew(MyMethod); task.Wait(); } static void MyMethod() { Console.WriteLine("This is a task running on a new thread."); } }
- 使用async/await关键字(基于Task):
using System; using System.Threading.Tasks; class Program { static async Task Main() { await MyMethodAsync(); } static async Task MyMethodAsync() { await Task.Run(() => { Console.WriteLine("This is an async method running on a new thread."); }); } }
这些示例展示了如何在C#中使用不同方法实现.NET Framework的多线程。请根据您的需求选择合适的方法。