线程基础 #
一、线程概述 #
1.1 什么是线程 #
线程是程序执行的最小单位,一个进程可以包含多个线程。
1.2 为什么使用多线程 #
- 提高响应性
- 并行处理
- 资源利用
二、Thread类 #
2.1 创建线程 #
csharp
var thread = new Thread(() =>
{
Console.WriteLine($"线程ID: {Thread.CurrentThread.ManagedThreadId}");
});
thread.Start();
var thread = new Thread(DoWork);
thread.Start();
void DoWork()
{
Console.WriteLine("工作线程执行中...");
}
2.2 带参数的线程 #
csharp
var thread = new Thread(DoWorkWithParam);
thread.Start("Hello");
void DoWorkWithParam(object? data)
{
Console.WriteLine($"收到数据: {data}");
}
2.3 线程属性 #
csharp
Thread thread = Thread.CurrentThread;
int id = thread.ManagedThreadId;
string name = thread.Name;
bool isBackground = thread.IsBackground;
ThreadPriority priority = thread.Priority;
ThreadState state = thread.ThreadState;
thread.Name = "MyThread";
thread.Priority = ThreadPriority.AboveNormal;
thread.IsBackground = true;
三、线程生命周期 #
3.1 线程状态 #
| 状态 | 说明 |
|---|---|
| Unstarted | 未启动 |
| Running | 运行中 |
| WaitSleepJoin | 等待中 |
| Stopped | 已停止 |
| Aborted | 已中止 |
3.2 线程控制 #
csharp
var thread = new Thread(() =>
{
Thread.Sleep(5000);
Console.WriteLine("线程完成");
});
thread.Start();
thread.Join();
thread.Join(1000);
Thread.Sleep(1000);
3.3 后台线程 #
csharp
var foregroundThread = new Thread(() =>
{
Thread.Sleep(5000);
Console.WriteLine("前台线程完成");
});
var backgroundThread = new Thread(() =>
{
Thread.Sleep(5000);
Console.WriteLine("后台线程完成");
});
backgroundThread.IsBackground = true;
foregroundThread.Start();
backgroundThread.Start();
四、线程同步基础 #
4.1 lock关键字 #
csharp
private readonly object _lock = new();
private int _counter = 0;
public void Increment()
{
lock (_lock)
{
_counter++;
}
}
4.2 Monitor类 #
csharp
private readonly object _lock = new();
public void DoWork()
{
Monitor.Enter(_lock);
try
{
}
finally
{
Monitor.Exit(_lock);
}
}
public void DoWorkWithTimeout()
{
if (Monitor.TryEnter(_lock, TimeSpan.FromSeconds(5)))
{
try
{
}
finally
{
Monitor.Exit(_lock);
}
}
}
4.3 Interlocked类 #
csharp
private int _counter = 0;
public void Increment()
{
Interlocked.Increment(ref _counter);
}
public void Decrement()
{
Interlocked.Decrement(ref _counter);
}
public void Add(int value)
{
Interlocked.Add(ref _counter, value);
}
public int GetAndSet(int newValue)
{
return Interlocked.Exchange(ref _counter, newValue);
}
五、线程安全集合 #
5.1 ConcurrentDictionary #
csharp
var dict = new ConcurrentDictionary<string, int>();
dict.TryAdd("张三", 85);
dict.AddOrUpdate("李四", 1, (key, oldValue) => oldValue + 1);
int value = dict.GetOrAdd("王五", 0);
bool removed = dict.TryRemove("张三", out int removedValue);
5.2 ConcurrentQueue #
csharp
var queue = new ConcurrentQueue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
if (queue.TryDequeue(out int result))
{
Console.WriteLine(result);
}
if (queue.TryPeek(out int peek))
{
Console.WriteLine(peek);
}
5.3 ConcurrentBag #
csharp
var bag = new ConcurrentBag<int>();
bag.Add(1);
bag.Add(2);
if (bag.TryTake(out int result))
{
Console.WriteLine(result);
}
六、线程池 #
6.1 ThreadPool类 #
csharp
ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine($"线程池线程: {Thread.CurrentThread.ManagedThreadId}");
});
ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine($"带参数: {state}");
}, "Hello");
ThreadPool.GetAvailableThreads(out int workerThreads, out int completionPortThreads);
ThreadPool.GetMaxThreads(out int maxWorkerThreads, out int maxCompletionPortThreads);
ThreadPool.SetMinThreads(10, 10);
6.2 线程池限制 #
csharp
public void ProcessWithThreadPool()
{
for (int i = 0; i < 100; i++)
{
int taskId = i;
ThreadPool.QueueUserWorkItem(_ =>
{
Console.WriteLine($"任务 {taskId} 在线程 {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(100);
});
}
}
七、实战示例 #
7.1 线程安全的计数器 #
csharp
public class ThreadSafeCounter
{
private int _count = 0;
private readonly object _lock = new();
public int Count
{
get { lock (_lock) { return _count; } }
}
public void Increment()
{
Interlocked.Increment(ref _count);
}
public void Decrement()
{
Interlocked.Decrement(ref _count);
}
public void Reset()
{
Interlocked.Exchange(ref _count, 0);
}
}
7.2 生产者消费者 #
csharp
public class ProducerConsumer<T>
{
private readonly Queue<T> _queue = new();
private readonly object _lock = new();
private readonly int _maxSize;
public ProducerConsumer(int maxSize = 100)
{
_maxSize = maxSize;
}
public void Produce(T item)
{
lock (_lock)
{
while (_queue.Count >= _maxSize)
{
Monitor.Wait(_lock);
}
_queue.Enqueue(item);
Monitor.PulseAll(_lock);
}
}
public T Consume()
{
lock (_lock)
{
while (_queue.Count == 0)
{
Monitor.Wait(_lock);
}
T item = _queue.Dequeue();
Monitor.PulseAll(_lock);
return item;
}
}
}
八、总结 #
线程基础要点:
| 要点 | 说明 |
|---|---|
| Thread | 线程类 |
| Start | 启动线程 |
| Join | 等待线程 |
| lock | 同步锁 |
| Interlocked | 原子操作 |
| ThreadPool | 线程池 |
下一步,让我们学习任务并行!
最后更新:2026-03-26