How to pass parameters to ThreadStart method in Thread?
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.
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.
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)
You could also delegate
like so...
ThreadStart ts = delegate
{
bool moreWork = DoWork("param1", "param2", "param3");
if (moreWork)
{
DoMoreWork("param1", "param2");
}
};
new Thread(ts).Start();