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類創建和管理線程。根據實際需求和情況選擇合適的方式來使用多線程。