Coder Perfect

How to pass parameters to ThreadStart method in Thread?

Problem

How to pass parameters to Thread.ThreadStart() method in C#?

Assume I have a ‘download’ method.

public void download(string filename)
{
    // download code
}

In the main function, I’ve now generated one thread:

Thread thread = new Thread(new ThreadStart(download(filename));

What is the best way to pass parameters to ThreadStart with a destination method that accepts parameters?

Asked by Swapnil Gupta

Solution #1

The easiest is to just

string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();

The benefit(s) of this (as opposed to ParameterizedThreadStart) is that you may pass numerous arguments and obtain compile-time validation without having to cast from object all of the time.

Answered by Marc Gravell

Solution #2

Consider the following scenario:

public void RunWorker()
{
    Thread newThread = new Thread(WorkerMethod);
    newThread.Start(new Parameter());
}

public void WorkerMethod(object parameterObj)
{
    var parameter = (Parameter)parameterObj;
    // do your job!
}

You start a thread by sending a delegate to the worker method, and then you start it with a Thread. Begin by calling a method that takes your object as a parameter.

As a result, in your case, you should utilize it as follows:

    Thread thread = new Thread(download);
    thread.Start(filename);

However, your ‘download’ method must take an object rather than a string as an argument. In the body of your method, you can cast it to string.

Answered by Ɓukasz W.

Solution #3

For thread methods that take parameters, you should use the ParameterizedThreadStart delegate. (Or none at all, and let the Thread constructor figure it out.)

Example usage:

var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent

thread.Start(filename)

Answered by Noldorin

Solution #4

You might also delegate in this manner…

ThreadStart ts = delegate
{
      bool moreWork = DoWork("param1", "param2", "param3");
      if (moreWork) 
      {
          DoMoreWork("param1", "param2");
      }
};
new Thread(ts).Start();

Answered by Magic Mick

Solution #5

In Additional

    Thread thread = new Thread(delegate() { download(i); });
    thread.Start();

Answered by Metin Atalay

Post is based on https://stackoverflow.com/questions/3360555/how-to-pass-parameters-to-threadstart-method-in-thread