.NET‎ > ‎

Ordered Thread Pool

A technique to make the .NET Thread Pool execute the queued tasks in order.

Read detailed article at my blog. [Home]
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace System.Threading
{
   public class OrderedThreadPool
   {
		private Queue workItemQ = new Queue();
		private bool loopWorkRunning = false;

		public void QueueUserWorkItem(WaitCallback wcbDelegate, object state)
		{
			lock (workItemQ)
			{
				workItemQ.Enqueue(new ThreadPoolTaskInfo(wcbDelegate, state));

				if (workItemQ.Count == 1 && !loopWorkRunning)
				{
					loopWorkRunning = true;
					ThreadPool.QueueUserWorkItem(LoopWork);
				}
			}
		}

		private void LoopWork(object notUsed)
		{
			WaitCallback wcb = null;
			object state = null;

			lock (workItemQ)
			{
				if (workItemQ.Count == 0)
				{
					loopWorkRunning = false;
					return;
				}

				ThreadPoolTaskInfo tptInfo = workItemQ.Dequeue();
				state = tptInfo.State;
				wcb = tptInfo.CallbackDelegate;
				Debug.Assert(wcb != null);
			}

			try
			{
				wcb(state);
			}
			finally
			{
				ThreadPool.QueueUserWorkItem(LoopWork, notUsed);
			}
		}
	  
		public struct ThreadPoolTaskInfo
		{
			public readonly WaitCallback CallbackDelegate;
			public readonly object State;

			public ThreadPoolTaskInfo(WaitCallback wc, object state)
			{
			 Debug.Assert(wc != null);
			 CallbackDelegate = wc;
			 State = state;
			}
		}
   }
}
Comments