I would not want to write chunks of code to spawns threads and perform many of my background tasks such as firing events, UI update etc. Instead I would use the System.Threading.ThreadPool class which serves this purpose. And a programmer who knows to use this class for such cases would also be aware that the tasks queued to the thread pool are NOT dispatched in the order they are queued. They get dispatched for execution in a haphazard fashion.
In some situations, it is required that the tasks queued to the thread pool are dispatched (and executed) in the order they were queued. For instance, in my (and most?) applications, a series of events are fired to notify the clients with what is happening inside the (server) application. Although the events may be fired from any thread (asynchronous), I would want them or rather the client would be expecting that the events are received in a certain order, which aligns with the sequence of steps carried out inside the server application for the requested service. So sequential execution of the queued tasks is not something one must not wish for.
Enough talking.......eat code.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Threading
{
struct ThreadPoolTaskInfo
{
public readonly WaitCallback CallbackDelegate;
public readonly object State;
public ThreadPoolTaskInfo(WaitCallback wc, object state)
{
Debug.Assert(wc != null);
CallbackDelegate = wc;
State = state;
}
}
class OrderedThreadPool
{
private Queue workItemQ = new Queue();
public void QueueUserWorkItem(WaitCallback wcbDelegate, object state)
{
lock (workItemQ)
{
workItemQ.Enqueue(new ThreadPoolTaskInfo(wcbDelegate, state));
if (workItemQ.Count == 1)
{
ThreadPool.QueueUserWorkItem(LoopWork);
}
}
}
private void LoopWork(object notUsed)
{
WaitCallback wcb = null;
object state = null;
lock (workItemQ)
{
if (workItemQ.Count == 0)
{
return;
}
ThreadPoolTaskInfo tptInfo = workItemQ.Dequeue();
state = tptInfo.State;
wcb = tptInfo.CallbackDelegate;
Debug.Assert(wcb != null);
}
try
{
wcb(state);
}
finally
{
ThreadPool.QueueUserWorkItem(LoopWork, notUsed);
}
}
}
}
The above class wraps the System.Threading.ThreadPool and offers the facility of execution of tasks in the order they are queued. Hope that is useful!
Comments
I think there is a small window for error in the OrderedThreadPool class.
Bascially, if an item of work is queued, then a worker thread runs, takes the item off the queue and is about to call wcb(state) - but at that instant is (say) context switched.
Then another item gets queued and another worker thread runs and dequeues the item and then again is about to call wcb(state).
There is scope here for the two operations to run concurrently or even out of order...
Do you agree or am I missing something?
Hugh
You are right. There is a window where the the execution could go out of order or concurrent.
I have fixed the issue here. Hope it really fixed the problem you pointed out.
Regards
Vivek Ragunathan