Nov 14

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 clients application. It automatically throttles the numbers of active threads by the number of processors. Unfortunately, the ThreadPool class was written before .NET 2 and therefore it does not take advantage of generics and you end up casting function methods and callback parameters back and forth. It can be a bit messy.

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

static class ThreadPoolHelper
{
  public delegate void Function();

  public static void Execute(Function function)
  {
    ThreadPool.QueueUserWorkItem(new WaitCallback(Call), (object)function);
  }

  private static void Call(object o)
  {
    ((Function)o)();
  }
}

 

With this code, to create a thread in the pool, you simple use:

TheadPoolHelper.Execute(someFunction);

 

Where someFunction is the name of a function method which does not have any parameters. 

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

static class ThreadPoolHelperWithParam<T>
{
  public delegate void Function(T param);

  public static void Execute(Function function, T param)
  {
    ThreadPool.QueueUserWorkItem(new WaitCallback(Call), new KeyValuePair<object, T>((object)function, param));
  }

  private static void Call(object o)
  {
    KeyValuePair<object, T> lObject = (KeyValuePair<object, T>)o;

    ((Function)lObject.Key)(lObject.Value);
  }
}

 

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

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:

Related posts

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Posted on Thursday, 28 August 2008 03:57