Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to ThreadStart method in Thread?

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?

like image 654
Swapnil Gupta Avatar asked Jul 29 '10 08:07

Swapnil Gupta


People also ask

What is ThreadStart?

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);

Why we need a ParameterizedThreadStart delegate?

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.

How do you close a thread in C#?

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.


1 Answers

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.

like image 187
Marc Gravell Avatar answered Oct 02 '22 09:10

Marc Gravell