How to pass parameters to Thread.ThreadStart()
method in C#?
Suppose I have method called 'download'
public void download(string filename) { // download code }
Now I have created one thread in the main method:
Thread thread = new Thread(new ThreadStart(download(filename));
error method type expected.
How can I pass parameters to ThreadStart
with target method with parameters?
Thread(ThreadStart) Constructor is used to initialize a new instance of a Thread class. This constructor will give ArgumentNullException if the value of the parameter is null. Syntax: public Thread(ThreadStart start);
Thread(ParameterizedThreadStart) Constructor is used to initialize a new instance of the Thread class. It defined a delegate which allows an object to pass to the thread when the thread starts. This constructor gives ArgumentNullException if the parameter of this constructor is null.
In C#, a thread can be terminated using Abort() method. Abort() throws ThreadAbortException to the thread in which it called. Due to this exception, the thread is terminated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With