Freigeben über


How to Pass Parameters to a Method on a New Thread

Most of you will find this relatively simple, but it took me a while to figure this out.  When executing a method on a new thread, I found it almost impossible to pass the method any parameters.  My code looked like below.

Method Signature to be Executed on Thread:

MyMethod(object parameter1)

Thread Creation:

Thread t = new Thread(new ThreadStart(MyMethod));

t.Start();

This would fail compilation because MyMethod expects a string parameter.  Enter the ParameterizedThreadStart delegate.

New Thread Creation:

Thread t = new Thread(new ParameterizedThreadStart(MyMethod));

t.Start(passedParameter1)

Thing to note here is that the method being used in this fashion needs to be passed an object.