如何在c#中传递参数给Thread.ThreadStart()方法?

假设我有一个叫做download的方法

public void download(string filename)
{
    // download code
}

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

Thread thread = new Thread(new ThreadStart(download(filename));

预期的方法类型错误。

我如何通过参数ThreadStart与目标方法参数?


当前回答

你需要为带参数的线程方法使用ParameterizedThreadStart委托。(或者实际上根本没有,让Thread构造函数来推断。)

使用示例:

var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent

thread.Start(filename)

其他回答

这样怎么样:(或者可以这样用吗?)

var test = "Hello";
new Thread(new ThreadStart(() =>
{
    try
    {
        //Staff to do
        Console.WriteLine(test);
    }
    catch (Exception ex)
    {
        throw;
    }
})).Start();

这里有一个完美的方法……

private void func_trd(String sender)
{

    try
    {
        imgh.LoadImages_R_Randomiz(this, "01", groupBox, randomizerB.Value); // normal code

        ThreadStart ts = delegate
        {
            ExecuteInForeground(sender);
        };

        Thread nt = new Thread(ts);
        nt.IsBackground = true;

        nt.Start();

    }
    catch (Exception)
    {

    }
}

private void ExecuteInForeground(string name)
{
     //whatever ur function
    MessageBox.Show(name);
}

你也可以这样委派…

ThreadStart ts = delegate
{
      bool moreWork = DoWork("param1", "param2", "param3");
      if (moreWork) 
      {
          DoMoreWork("param1", "param2");
      }
};
new Thread(ts).Start();

您可以将线程函数(下载)和所需的参数(文件名)封装在一个类中,并使用ThreadStart委托来执行线程函数。

public class Download
{
    string _filename;

    Download(string filename)
    {
       _filename = filename;
    }

    public void download(string filename)
    {
       //download code
    }
}

Download = new Download(filename);
Thread thread = new Thread(new ThreadStart(Download.download);

最简单的就是

string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();

这样做(相对于ParameterizedThreadStart)的优点是可以传递多个参数,并且可以进行编译时检查,而不需要一直从object进行强制转换。