Click here to Skip to main content
Click here to Skip to main content

Tagged as

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");
        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)

Share

About the Author

DaveyM69
CEO Dave Meadowcroft
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
GeneralReason for my vote of 5 Very nice! Pinmemberbelamate28-Mar-11 16:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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.1411022.1 | Last Updated 22 Mar 2011
Article Copyright 2010 by DaveyM69
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid