Skip to content

Instantly share code, notes, and snippets.

@junwin
Created February 7, 2013 15:13
Show Gist options
  • Save junwin/4731525 to your computer and use it in GitHub Desktop.
Save junwin/4731525 to your computer and use it in GitHub Desktop.
Simple C# worker thread that processes a queue of string data items (XML, JSON )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections;
namespace workerthread
{
public class Test
{
/// <summary>
/// Worker thread to peform compiles
/// </summary>
private WorkerThread _workerThread;
private Thread _procWorkerThread;
// Queue of ruleapps to compile
private Queue<string> _requestQueue;
// used t indicate things are added to the queue for the worker thread
private SyncEvents _syncEvents;
public Test()
{
// Worker thread support
_requestQueue = new Queue<string>();
_syncEvents = new SyncEvents();
_workerThread = new WorkerThread(_requestQueue, _syncEvents);
_procWorkerThread = new Thread(_workerThread.ThreadRun);
_procWorkerThread.Start();
}
public void doWork(string stateData)
{
try
{
// do the update assync
lock (((ICollection)_requestQueue).SyncRoot)
{
// add the data to work on in the queue
// could be xml or JSON
_requestQueue.Enqueue(stateData);
// signal the worker thread to process queue
_syncEvents.NewItemEvent.Set();
}
}
catch
{
}
}
}
public class WorkerThread
{
private Queue<string> _queue;
private SyncEvents _syncEvents;
public WorkerThread(Queue<string> q, SyncEvents e)
{
_queue = q;
_syncEvents = e;
}
// Consumer.ThreadRun
public void ThreadRun()
{
Queue<string> myWorkQueue = new Queue<string>();
while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)
{
lock (((ICollection)_queue).SyncRoot)
{
while (_queue.Count > 0)
{
myWorkQueue.Enqueue(_queue.Dequeue());
}
}
while (myWorkQueue.Count > 0)
{
string myData = myWorkQueue.Dequeue();
// DO WORK WITH DATA HERE
}
}
}
}
public class SyncEvents
{
private EventWaitHandle _newItemEvent;
private EventWaitHandle _exitThreadEvent;
private WaitHandle[] _eventArray;
public SyncEvents()
{
_newItemEvent = new AutoResetEvent(false);
_exitThreadEvent = new ManualResetEvent(false);
_eventArray = new WaitHandle[2];
_eventArray[0] = _newItemEvent;
_eventArray[1] = _exitThreadEvent;
}
public EventWaitHandle ExitThreadEvent
{
get { return _exitThreadEvent; }
}
public EventWaitHandle NewItemEvent
{
get { return _newItemEvent; }
}
public WaitHandle[] EventArray
{
get { return _eventArray; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment