tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Event when ThreadPool finishes processing an item

29 Jun 2013 1 mins .NET, C#, Multithreading/Parallelism/Asynchronous/Concurrency

Yesterday I was doing my parallel-threading-async-locking course and at one time we discussed (unplanned) Thread Local Storage (TLS) with one participant. To make a long story short they needed to know when processing of some item in ThreadPool completed. The default implementation of ThreadPool doesn’t have such event, but luckily we can create such one. I sketched this in under five minutes and I think it might be worth for others.

It’s just a proof of concept. But you can change it for you specific usage. If you dive deep (enough) you’ll more or less end up with Task object. 😃

class MyThreadPool
{
	public static event EventHandler OperationCompleted;

	public static void QueueUserWorkItem(WaitCallback operation, object state)
	{
		ThreadPool.QueueUserWorkItem(o =>
			{
				try
				{
					operation(o);
				}
				finally
				{
					OnOperationCompleted();
				}
			}, state);
	}

	static void OnOperationCompleted()
	{
		if (OperationCompleted != null)
			OperationCompleted(null, EventArgs.Empty);
	}
}

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.