c# - How to pass parameters to ThreadStart method in Thread?

ID : 10149

viewed : 18

Tags : c#.netmultithreadingc#

Top 5 Answer for c# - How to pass parameters to ThreadStart method in Thread?

vote vote

92

The simplest is just

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

The advantage(s) of this (over ParameterizedThreadStart) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object all the time.

vote vote

83

Look at this example:

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 are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.

So in your case you should use it like this:

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

But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

vote vote

75

You want to use the ParameterizedThreadStart delegate for thread methods that take parameters. (Or none at all actually, and let the Thread constructor infer.)

Example usage:

var thread = new Thread(new ParameterizedThreadStart(download)); //var thread = new Thread(download); // equivalent  thread.Start(filename) 
vote vote

70

You could also delegate like so...

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

51

In Additional

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

Top 3 video Explaining c# - How to pass parameters to ThreadStart method in Thread?

Related QUESTION?