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.
public delegate void ParameterizedThreadStart<T>(T value);
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);
}
public void Start(T value)
{
thread.Start(value);
}
}
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);
}
}