C# 中,ConcurrentQueue<T>
, ConcurrentBag<T>
, ConcurrentDictionary<TKey, TValue>
, BlockingCollection<T>
, lock
, Mutex
, SemaphoreSlim
等。下面是它们的详细介绍和相应的代码示例。
1. 线程安全队列
ConcurrentQueue<T>
ConcurrentQueue<T>
是一个线程安全的先进先出(FIFO)队列,适用于在多线程环境中进行高效的入队和出队操作。
示例代码:
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
public class ConcurrentQueueExample
{
private ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
public void Producer()
{
for (int i = 0; i < 10; i++)
{
queue.Enqueue(i);
Console.WriteLine($"Produced: {i}");
Thread.Sleep(100); // 模拟生产延迟
}
}
public void Consumer()
{
while (true)
{
if (queue.TryDequeue(out int item))
{
Console.WriteLine($"Consumed: {item}");
Thread.Sleep(200); // 模拟消费延迟
}
else
{
Thread.Sleep(50); // 暂时无数据,稍等
}
}
}
public static void Main()
{
var example = new ConcurrentQueueExample();
Task.Run(() => example.Producer());
Task.Run(() => example.Consumer());
Console.ReadLine(); // 等待用户输入以保持应用程序运行
}
}
2. 线程安全集合
ConcurrentBag<T>
ConcurrentBag<T>
是一个线程安全的集合,允许在多个线程中高效地添加和移除项目,适用于需要不排序的集合的场景。
示例代码:
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
public class ConcurrentBagExample
{
private ConcurrentBag<int> bag = new ConcurrentBag<int>();
public void AddItems()
{
for (int i = 0; i < 10; i++)
{
bag.Add(i);
Console.WriteLine($"Added: {i}");
Thread.Sleep(100); // 模拟添加延迟
}
}
public void TakeItems()
{
while (true)
{
if (bag.TryTake(out int item))
{
Console.WriteLine($"Taken: {item}");
Thread.Sleep(200); // 模拟处理延迟
}
else
{
Thread.Sleep(50); // 暂时无数据,稍等
}
}
}
public static void Main()
{
var example = new ConcurrentBagExample();
Task.Run(() => example.AddItems());
Task.Run(() => example.TakeItems());
Console.ReadLine(); // 等待用户输入以保持应用程序运行
}
}
ConcurrentDictionary<TKey, TValue>
ConcurrentDictionary<TKey, TValue>
是一个线程安全的键值对集合,允许多个线程同时读写字典。
示例代码:
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
public class ConcurrentDictionaryExample
{
private ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
public void AddItems()
{
for (int i = 0; i < 10; i++)
{
dictionary.TryAdd(i, $"Value {i}");
Console.WriteLine($"Added: Key={i}, Value=Value {i}");
Thread.Sleep(100); // 模拟添加延迟
}
}
public void ReadItems()
{
while (true)
{
foreach (var kvp in dictionary)
{
Console.WriteLine($"Key={kvp.Key}, Value={kvp.Value}");
}
Thread.Sleep(500); // 模拟读取延迟
}
}
public static void Main()
{
var example = new ConcurrentDictionaryExample();
Task.Run(() => example.AddItems());
Task.Run(() => example.ReadItems());
Console.ReadLine(); // 等待用户输入以保持应用程序运行
}
}
3. 线程安全同步机制
lock
关键字
lock
是用于确保同一时间只能有一个线程访问特定代码块的机制。
示例代码:
using System;
using System.Threading;
public class LockExample
{
private readonly object lockObject = new object();
private int sharedResource;
public void AccessResource()
{
lock (lockObject)
{
// 线程安全地访问或修改共享资源
sharedResource++;
Console.WriteLine($"Shared Resource: {sharedResource}");
}
}
public static void Main()
{
var example = new LockExample();
Thread thread1 = new Thread(() => example.AccessResource());
Thread thread2 = new Thread(() => example.AccessResource());
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
}
Mutex
Mutex
是一个更强大的同步工具,适用于在进程间进行线程同步。
示例代码:
using System;
using System.Threading;
public class MutexExample
{
private static Mutex mutex = new Mutex();
public void AccessResource()
{
mutex.WaitOne(); // 请求获取互斥锁
try
{
// 线程安全地访问共享资源
Console.WriteLine($"Resource accessed by {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(1000); // 模拟处理时间
}
finally
{
mutex.ReleaseMutex(); // 释放互斥锁
}
}
public static void Main()
{
var example = new MutexExample();
Thread thread1 = new Thread(() => example.AccessResource());
Thread thread2 = new Thread(() => example.AccessResource());
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
}
SemaphoreSlim
SemaphoreSlim
是一个轻量级的线程同步机制,用于限制同时访问某些资源的线程数量。
示例代码:
using System;
using System.Threading;
using System.Threading.Tasks;
public class SemaphoreSlimExample
{
private static SemaphoreSlim semaphore = new SemaphoreSlim(2); // 允许最多两个线程同时访问
public async Task AccessResourceAsync()
{
await semaphore.WaitAsync(); // 请求获取信号量
try
{
// 线程安全地访问共享资源
Console.WriteLine($"Resource accessed by {Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(1000); // 模拟处理时间
}
finally
{
semaphore.Release(); // 释放信号量
}
}
public static async Task Main()
{
var example = new SemaphoreSlimExample();
Task[] tasks = new Task[5];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = example.AccessResourceAsync();
}
await Task.WhenAll(tasks);
}
}