Skip to content

Instantly share code, notes, and snippets.

@jakesays-old
Created October 29, 2013 05:09
Show Gist options
  • Save jakesays-old/7209414 to your computer and use it in GitHub Desktop.
Save jakesays-old/7209414 to your computer and use it in GitHub Desktop.
SuperQueue
void Main()
{
}
// Define other methods and classes here
public class SuperQueue<TElement>
{
private Queue<TElement> _queue1 = new Queue<TElement>();
private Queue<TElement> _queue2 = new Queue<TElement>();
private ReaderWriterLockSlim _producerGuard = new ReaderWriterLockSlim();
private Queue<TElement> _producerQueue = _queue1;
public void Enqueue(TElement item)
{
try
{
_producerGuard.EnterReadLock();
_producerQueue.Enqueue(item);
}
finally
{
_producerGuard.ExitReadLock();
}
}
public void Consume(Action<TElement> consumer)
{
Queue<TElement> currentQueue = null;
try
{
_producerGuard.EnterWriteLock();
currentQueue = _producerQueue;
if (currentQueue == _queue1)
{
_producerQueue = _queue2;
}
else
{
_producerQueue = _queue1;
}
}
finally
{
_producerGuard.ExitWriteLock();
}
while (currentQueue.Count > 0)
{
consumer(currentQueue.Dequeue());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment