Skip to content

Instantly share code, notes, and snippets.

@dkellycollins
Last active December 12, 2015 03:09
Show Gist options
  • Save dkellycollins/4705004 to your computer and use it in GitHub Desktop.
Save dkellycollins/4705004 to your computer and use it in GitHub Desktop.
QueueProccessor for processing data. This class is meant to be inherited and have the sub class handle actually processing the data. Currently implemented with BackgroundWorker and is untested.
///<summary>
///Handles processing data of type T. Subclass implements process and handles storing results.
///</summary>
public abstract class QueueProcessor<T>
{
private Queue<T> _data;
private BackgroundWorker _worker;
private bool _stopOnEmpty;
public delegate ErrorHandler(Exception e);
///<summary>
///Raised when there is an error processing data.
///</summary>
public event ErrorHandler Error = delegate {};
///<summary>
///Creates a new processor.
///</summary>
public QueueProcessor()
{
_data = new Queue<T>();
_worker = new BackgroundWorker();
_worker.DoWork += new DoWorkEventHandler(worker_DoWork);
}
///<summary>
///Adds given data to the queue.
///</summary>
///<param name=data>Data to queue for processing.</param>
public void QueueData(T data)
{
lock(_data)
{
_data.enqueue(data);
}
}
///<summary>
///Starts the processor.
///</summary>
///<param name=stopOnEmpty>If true, processor will stop once the queue is empty.</param>
public void Start(bool stopOnEmpty = false)
{
_stopOnEmpty = stopOnEmpty;
if(!_worker.IsBusy)
_worker.RunWorkerAsync();
}
///<summary>
///Stops the processor.
///</summary>
public void Stop()
{
if(_worker.IsBusy)
_worker.CancelAsync();
}
///<summary>
///Stop any current processing and clears all data.
///</summary>
public void Reset()
{
Stop();
_data.Clear();
}
//Handles dequeue data and calling process.
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
while(!e.CancellationPending)
{
if(_data.Count == 0)
{
if(_stopOnEmpty)
break;
else
continue;
}
try
{
T data;
lock(_data)
{
data = _data.Dequeue();
}
process(data);
}
catch(Exception e)
{
Error(e);
}
}
}
//process method to be implemented by subclass.
protected abstract void process(T data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment