1. 使用 Thread 类(基础方式)
using System;
using System.Threading;
class Program
{
static void Main()
{
// 创建并启动新线程
Thread workerThread = new Thread(DoWork);
workerThread.Start();
// 主线程继续执行
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"主线程: {i}");
Thread.Sleep(100);
}
workerThread.Join(); // 等待工作线程结束
}
static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"工作线程: {i}");
Thread.Sleep(200);
}
}
}2. 使用线程池 (ThreadPool)
适合短任务,避免频繁创建/销毁线程开销。
ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine($"线程池线程ID: {Thread.CurrentThread.ManagedThreadId}");
// 执行任务...
});3. 使用 Task (推荐方式)
基于 TPL (Task Parallel Library),更高效且支持异步。
Task.Run(() =>
{
Console.WriteLine($"Task 线程ID: {Thread.CurrentThread.ManagedThreadId}");
// 执行任务...
});
// 等待任务完成
var task = Task.Run(() => CalculateResult());
task.Wait();
Console.WriteLine($"结果: {task.Result}");
// 异步方法中使用
async Task ProcessDataAsync()
{
await Task.Run(() => HeavyComputation());
}4. 使用 Parallel 类
Parallel.For(0, 10, i =>
{
Console.WriteLine($"并行循环: {i}, 线程ID: {Thread.CurrentThread.ManagedThreadId}");
});
string[] data = { "A", "B", "C", "D" };
Parallel.ForEach(data, item =>
{
Console.WriteLine($"处理: {item}");
});5. 异步编程 (async/await)
适合 I/O 密集型操作,非阻塞主线程。
async Task DownloadAsync()
{
using (HttpClient client = new HttpClient())
{
string result = await client.GetStringAsync("https://example.com");
Console.WriteLine(result);
}
}
// 调用
await DownloadAsync();6. 同步机制(线程安全)
lock 关键字
private static readonly object _lock = new object();
static int _counter = 0;
void Increment()
{
lock (_lock)
{
_counter++;
}
}Mutex / Semaphore / Monitor
更高级的同步原语(跨进程时用 Mutex)。
7. 取消操作 (CancellationToken)
var cts = new CancellationTokenSource();
Task.Run(() =>
{
while (!cts.Token.IsCancellationRequested)
{
Console.WriteLine("工作中...");
Thread.Sleep(500);
}
}, cts.Token);
// 2秒后取消任务
await Task.Delay(2000);
cts.Cancel();8. ValueTask 优化性能
适合高频调用的异步方法,减少内存分配。
public ValueTask<int> FastPathAsync()
{
return new ValueTask<int>(42); // 直接返回结果
}