C#中使用多线程的几种方式有以下几种:
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread = new Thread(DoWork);
thread.Start();
// 主线程继续执行其他操作
Console.WriteLine("Main thread is working...");
// 等待子线程结束
thread.Join();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("Child thread is working...");
// 模拟耗时操作
Thread.Sleep(2000);
Console.WriteLine("Child thread completed.");
}
}
using System;
using System.Threading;
class Program
{
static void Main()
{
ThreadPool.QueueUserWorkItem(DoWork);
// 主线程继续执行其他操作
Console.WriteLine("Main thread is working...");
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static void DoWork(object state)
{
Console.WriteLine("Child thread is working...");
// 模拟耗时操作
Thread.Sleep(2000);
Console.WriteLine("Child thread completed.");
}
}
using System;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Task task = Task.Run(DoWork);
// 主线程继续执行其他操作
Console.WriteLine("Main thread is working...");
// 等待任务完成
task.Wait();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("Child thread is working...");
// 模拟耗时操作
Task.Delay(2000).Wait();
Console.WriteLine("Child thread completed.");
}
}
以上示例分别使用了Thread类、ThreadPool类和Task类创建和管理线程。根据实际需求和情况选择合适的方式来使用多线程。