Skip to content

Instantly share code, notes, and snippets.

@CodingGorilla
Created January 26, 2012 16:13
Show Gist options
  • Save CodingGorilla/1683547 to your computer and use it in GitHub Desktop.
Save CodingGorilla/1683547 to your computer and use it in GitHub Desktop.
Code sample for StackOverflow question 9019961
public class Com<T>
{
private Thread dispatcher;
private Queue<T> queue;
private int waitTime;
private Object locker;
private Timer timer;
private ManualResetEvent event;
public event EventHandler EmptyQueueEvent;
public Com()
{
queue = new Queue<T>();
locker = new Object();
waitTime = X;
timer = new Timer(FireEmpty, null, Timeout.Infinite,Timeout.Infinite);
dispatcher = new Thread(Serve);
dispatcher.IsBackground = true;
dispatcher.Start();
event = new ManualResetEvent(false);
}
private void Serve()
{
while (true)
{
int count = 0;
lock(locker)
count = queue.Count;
if (count == 0)
{
event.WaitOne(); // Wait for Add() to signal us
}
lock(locker)
count = queue.Count;
while (count != 0)
{
lock (locker)
{
deliver(queue.Dequeue());
count = queue.Count;
}
}
// Reset to non-signaled state so the next loop iteration
// goes into the wait state waiting on Add()
event.Reset();
}
}
private void deliver(T item)
{
// Do stuff
}
public void Add(T item)
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
lock (locker)
{
queue.Enqueue(item);
}
event.Set(); // Signal Serve() that there is work to be done
}
private void FireEmpty(object o)
{
//Fire Event
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment