Developer, Former MVP, now at Microsoft - Best of 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
// declarations
private Thread mSendNextThread; // worker thread
private bool mStayAlive; // for controlling the thread termination
private Queue mQue; // buffer of jobs
private ManualResetEvent mWaitEvent;// signal the thread to wake up
// Initialisation logic
public void Start(){
Console.WriteLine("*********");
Console.WriteLine("Start");
mQue = new Queue();
mWaitEvent = new ManualResetEvent(false);
mStayAlive = true;
mSendNextThread = new Thread(new ThreadStart(OnMyOwnThread));
mSendNextThread.Start();
}
// Tear down logic
public void Stop(){
Console.WriteLine("Stop request");
lock (mQue.SyncRoot){
mQue.Clear();
// kill the thread
mWaitEvent.Reset();
Thread.Sleep(10);
mStayAlive = false;
mWaitEvent.Set();
mSendNextThread = null;
Console.WriteLine("Stopped");
// queue more jobs
public void MoreInput(object someInput){
Console.WriteLine("More Input: " + someInput.ToString());
mQue.Enqueue(someInput);
// process jobs
public void OnMyOwnThread(){
while (mStayAlive){
if (mWaitEvent.WaitOne()){
while (mQue.Count > 0){ //Whether we do the looping depends
//on the specifics of DoWork
if (!mStayAlive){
break;
this.DoWork2();
Console.WriteLine("Thread exiting");
private void DoWork2(){
object queObj = null;
if (mQue.Count > 0){
queObj = mQue.Dequeue();
// do some long processing with this job/input
if (queObj != null){
Console.WriteLine("Processing: " + queObj.ToString());
Thread.Sleep(300);//LONG PROCESSING
Console.WriteLine("Processed " + Environment.TickCount.ToString());