Passing Parameters to ThreadStart from Main Thread
When creating a new thread and passing parameters to its target method, it's essential to understand the syntax and options available in C#. Consider the following scenario:
<br>public void download(string filename)<br>{</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// download code
}
Thread thread = new Thread(new ThreadStart(download(filename)));
However, this code will result in a compilation error, as the ThreadStart constructor expects a method with no parameters. So, how can we pass parameters to the ThreadStart method from the main thread?
Simplest Approach: Lambda Expression
The simplest solution is to use a lambda expression as the target method, as seen below:
string filename = ... Thread thread = new Thread(() => download(filename)); thread.Start();
This technique allows you to pass multiple parameters to the target method and provides compile-time checking without the need for casting from objects.
The above is the detailed content of How to Pass Parameters to a ThreadStart Method in C#?. For more information, please follow other related articles on the PHP Chinese website!