Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Generic Thread Start

4.67/5 (6 votes)
22 Mar 2011CPOL 1  
Starting a thread using a generic argument
Yesterday, I had the need for a generic method to be called by a ParameterizedThreadStart delegate. This delegate (and the method to be invoked of course) take an object rather than T.

This is a quick and dirty wrapper around the Thread class and a generic version of the delegate to enable the use of generics.

Note: The value is still boxed and unboxed in the wrapper class.

C#
// ParameterizedThreadStart.cs
public delegate void ParameterizedThreadStart<T>(T value);

// ParameterizedThread.cs
using System.Threading;

public class ParameterizedThread<T>
{
    private ParameterizedThreadStart<T> parameterizedThreadStart;
    private Thread thread;

    public ParameterizedThread(ParameterizedThreadStart<T> start)
    {
        parameterizedThreadStart = start;
        thread = new Thread(new ParameterizedThreadStart(Start));
    }

    public Thread Thread
    {
        get { return thread; }
    }

    private void Start(object obj)
    {
        parameterizedThreadStart.Invoke((T)obj); // Unboxing
    }
    public void Start(T value)
    {
        thread.Start(value); // Boxing
    }
}

Here is a quick example of usage:
C#
using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Thread ID: {0}, Start", Thread.CurrentThread.ManagedThreadId);
        ParameterizedThread<string> threadOne = new ParameterizedThread<string>(
            new ParameterizedThreadStart<string>(WriteValue));
        ParameterizedThread<int> threadTwo = new ParameterizedThread<int>(
            new ParameterizedThreadStart<int>(WriteValue));
        threadOne.Start("Hello World");
        threadTwo.Start(123);
        Console.ReadKey();
    }

    static void WriteValue<T>(T value)
    {
        Console.WriteLine("Thread ID: {0}, {1}", Thread.CurrentThread.ManagedThreadId, value);
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)