Is The following Code valid it is like a mini thread pool(a friend at
work wrote it)?
I have cut down the code a bit but kept the essential parts.
The main part that I am would like explainedis when the async callback
gets called and the the line
m_WaitCallback.EndInvoke(AsyncResult);
How does it know which method has ended. i.e. does the AsyncResult
identify it?? Is it accepable to have one member variable used for all
of the begininvoke calls.
Thanks for any help,
Nick
public class SerialisedWorkerQueue
{
private WaitCallback m_WaitCallback;
private Queue m_Queue;
private int m_AvailableThreads;
private int m_ThreadsInUse;
public SerialisedWorkerQueue()
{
m_WaitCallback=new WaitCallback
(PerformWork_Internal);
m_Queue=new Queue();
m_AvailableThreads=5;
m_ThreadsInUse=0;
}
public void Add(object WorkerItem)
{
m_Queue.Enqueue(WorkerItem);
if (m_ThreadsInUse<m_AvailableThreads)
SpawnWork(null);
}
private void SpawnWork(IAsyncResult AsyncResult)
{
lock(this)
{
if(AsyncResult!=null)
{
m_WaitCallback.EndInvoke(AsyncResult);
m_ThreadsInUse--;
}
// oWorker item will be null if the queue was empty
if(m_Queue.Count>0)
{
m_ThreadsInUse++;
//Gets the next piece of work to perform
object oWorkerItem = m_Queue.Dequeue();
//Hooks up the callback to this method.
AsyncCallback oAsyncCallback = new AsyncCallback(this.SpawnWork);
//Invokes the work on the threadpool
m_WaitCallback.BeginInvoke(oWorkerItem,oAsyncCallb ack,null);
}
}
}
private void PerformWork_Internal(object WorkerItem)
{
//Do Work...
}
}