最近在維護一些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