Created
January 26, 2012 16:13
-
-
Save CodingGorilla/1683547 to your computer and use it in GitHub Desktop.
Code sample for StackOverflow question 9019961
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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