C#支持多线程的安全队列
在C#中,可以使用ConcurrentQueue
使用ConcurrentQueue
下面是一个使用ConcurrentQueue
using System;
using System.Collections.Concurrent;
using System.Threading;
class Program
{
static ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
static void Main()
{
// 启动两个线程向队列中添加数据
Thread t1 = new Thread(EnqueueElements);
Thread t2 = new Thread(EnqueueElements);
t1.Start();
t2.Start();
// 启动一个线程从队列中移除数据
Thread t3 = new Thread(DequeueElements);
t3.Start();
// 等待所有线程执行完毕
t1.Join();
t2.Join();
t3.Join();
}
static void EnqueueElements()
{
for (int i = 0; i < 100; i++)
{
queue.Enqueue(i);
Console.WriteLine("Enqueued: " + i);
Thread.Sleep(100); // 模拟耗时操作
}
}
static void DequeueElements()
{
int value;
while (!queue.IsEmpty)
{
if (queue.TryDequeue(out value))
{
Console.WriteLine("Dequeued: " + value);
Thread.Sleep(100); // 模拟耗时操作
}
}
}
}
在上面的示例中,使用ConcurrentQueue
原文地址: https://www.cveoy.top/t/topic/hYEp 著作权归作者所有。请勿转载和采集!