轻量级 Lock Free 线程安全的 Queue<T> 的C#2.0实现
最近在维护一些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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步