如何传递参数的ThreadStart方法主题?参数、方法、主题、ThreadStart

2023-09-02 01:22:11 作者:伴迩如伴狗

如何通过在C#中的参数 Thread.ThreadStart()的方法?

假设我有办法叫下载

 公共无效下载(字符串文件名)
{
    //下载code
}
 

在main方法现在,我已经创建了一个线程:

 线程的线程=新主题(新的ThreadStart(下载(文件名));
 

  

错误方法类型的预期。

我如何可以传递参数给的ThreadStart ,目标方法的参数?

解决方案

最简单的就是

 字符串文件名= ...
线程线程=新主题(()=>下载(文件名));
thread.Start();
 
C 方法 参数传递 略提

的优势(S)这个(超过 ParameterizedThreadStart )是可以传递多个参数,你会得到编译时检查,而不需要投从对象所有的时间。

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 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?

解决方案

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.