轻量级 Lock Free 线程安全的 Queue<T> 的C#2.0实现

本文介绍了一个适用于C#2.0的线程安全队列实现,该实现使用了Interlocked原子操作来替代传统的lock关键字,确保了在多线程环境下队列操作的安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在维护一些C# 2.0的代码....发现各种线程不安全的实现

2.0里面又没有ConcurrentCollection的相关类

不得已,自己写了一个,

本来想用传统的lock实现的, 不过考虑到其中的操作非常轻量级...最终还是用了Lock Free

使用原子操作 InterLocked 替换掉常用的lock关键字

    public sealed class SafedQueue<T>
{
#region private Fields
private int isTaked = 0;
private Queue<T> queue = new Queue<T>();
private int MaxCount = 1000 * 1000;
#endregion

public void Enqueue(T t)
{
try
{
while (Interlocked.Exchange(ref isTaked, 1) != 0)
{
}
this.queue.Enqueue(t);
}
finally
{
Thread.VolatileWrite(ref isTaked, 0);
}
}

public T Dequeue()
{
try
{
while (Interlocked.Exchange(ref isTaked, 1) != 0)
{
}
T t = this.queue.Dequeue();
return t;
}
finally
{
Thread.VolatileWrite(ref isTaked, 0);
}
}

public bool TryEnqueue(T t)
{
try
{
for (int i = 0; i < MaxCount; i++)
{
if (Interlocked.Exchange(ref isTaked, 1) == 0)
{
this.queue.Enqueue(t);
return true;
}
}
return false;
}
finally
{
Thread.VolatileWrite(ref isTaked, 0);
}
}

public bool TryDequeue(out T t)
{
try
{
for (int i = 0; i < MaxCount; i++)
{
if (Interlocked.Exchange(ref isTaked, 1) == 0)
{
t = this.queue.Dequeue();
return true;
}
}
t = default(T);
return false;
}
finally
{
Thread.VolatileWrite(ref isTaked, 0);
}
}
}

Try起头的方法都有尝试次数限制,超过限制以后就退出并返回false

转载于:https://www.cnblogs.com/PurpleTide/archive/2012/03/18/2404608.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值