Click here to Skip to main content
15,881,687 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Generic Thread Start

Rate me:
Please Sign up or sign in to vote.
4.67/5 (6 votes)
22 Mar 2011CPOL 19.2K   11   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)


Written By
CEO Dave Meadowcroft
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 Very nice! Pin
belamate28-Mar-11 15:36
belamate28-Mar-11 15:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.