Event when ThreadPool finishes processing an item
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);
}
}