Click here to Skip to main content
11,932,461 members (55,385 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


11 bookmarked

Generic Thread Start

, 22 Mar 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

// 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:
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");
    static void WriteValue<T>(T value)
        Console.WriteLine("Thread ID: {0}, {1}", Thread.CurrentThread.ManagedThreadId, value);


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


About the Author

CEO Dave Meadowcroft
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralReason for my vote of 5 Very nice! Pin
belamate28-Mar-11 16:36
memberbelamate28-Mar-11 16: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.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151126.1 | Last Updated 22 Mar 2011
Article Copyright 2010 by DaveyM69
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid