ThreadPool Helper Class

by Phil 10. May 2009 06:42

Lately, I have written a lot of multithreaded code in C#. I use the ThreadPool class object to launch and manage many parallel threads - mostly for TCP communications with client applications. It automatically throttles the numbers of active threads by the number of processors. Unfortunately, the ThreadPool class was written before .NET 2.0 and therefore it does not take advantage of generics. So you end up casting function methods and callback parameters. It can be a bit messy.

However, you can simplify things with the following helper class:

   1: static class ThreadPoolHelper
   2: {
   3:     public delegate void Function();
   4:  
   5:     public static void Execute(Function function)
   6:     {
   7:         ThreadPool.QueueUserWorkItem(new WaitCallback(Call), (object)function);
   8:     }
   9:  
  10:     private static void Call(object o)
  11:     {
  12:         ((Function)o)();
  13:     }
  14: }

To create a thread in the pool with this helper class, you simple use:

   1: TheadPoolHelper.Execute(someFunction);

Where someFunction is the name of a function method. 

If you need to pass a parameter, here's the helper class for that too:

   1: static class ThreadPoolHelperWithParam<T>
   2: {
   3:     public delegate void Function(T param);
   4:  
   5:     public static void Execute(Function function, T param)
   6:     {
   7:         ThreadPool.QueueUserWorkItem(new WaitCallback(Call), new KeyValuePair<object, T>((object)function, param));
   8:     }
   9:  
  10:     private static void Call(object o)
  11:     {
  12:         KeyValuePair<object, T> lObject = (KeyValuePair<object, T>)o;
  13:  
  14:         ((Function)lObject.Key)(lObject.Value);
  15:     }
  16: }

Now you can also pass an object of any type, like this:

   1: ThreadPoolHelperWithParam<someObjectType>.Execute(someMethod, someObject); 

 

Where the someObjectType is the type of object you are passing, and someObject with actual object you wish to pass as a parameter. Simple!

Tags:

Code

Comments are closed

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen | Modified by Mooglegiant

Projects

Software Stack

Recent Comments

Comment RSS

Badges

Enhanced with Snapshots