Thursday, September 10, 2009

Thread Pooling

I have to take care of multiple printers in my application. The "Print Manager" receives a list of jobs which is basically an XML file of a simple structure - a number of PrintJob nodes. Each print job has a printer assigned to it.

The Print Manager has to send each job to the appropriate printer, and also notify the sender of the XML of the completion or failure of each job. I'm sure tasks like these are common but somehow could not find good suggestions on implementing this one. I found a Miscellaneous Utility Library though (written by Jon Skeet himself by the way) which implemented a class called "CustomThreadPool", which allows creating multiple thread pools in a .NET application.

So, my approach so far is as follows: Get a print job. If a pool exists for this printer, place the job in a thread in the pool. Otherwise, create a pool and place the job in a thread in this pool. Get next job.

Here is how it looks like so far:

private List _printerThreads = new List();

delegate Errors ThreadMethod(PrintJob job);

private Errors InsertThread(PrintJob job)
{
ProcessSinglePrintJob(job);
}

// stuff ...

public void ProcessPrintJobs()
{
if (_printJobs != null)
{
foreach (PrintJob printJob in _printJobs)
{
if(String.IsNullOrEmpty(printJob.PrinterName))
{
printJob.JobResult = Errors.PrinterNameNotSpecified;
}
else if (String.IsNullOrEmpty(printJob.ReaderName) && printJob.IsEncodeSmartCard)
{
printJob.JobResult = Errors.SmartCardReaderNameNotSpecified;
}
else
{
CustomThreadPool pool = _printerThreads.Find(delegate(CustomThreadPool test)
{
return test.Name == printJob.PrinterName;
});

if (pool == null)
{
pool = new CustomThreadPool(printJob.PrinterName);
}

ThreadMethod method = new ThreadMethod(InsertThread);

pool.AddWorkItem(method, printJob);
}
}
}
}

I don't have extensive experience with multithreading so this solution might not even work or it may be too complex for the task. I'll run some tests soon anyway with the actual printers.

by . Also posted on my website

No comments: