根据你的问题...
C#中如何给Thread.ThreadStart()方法传递参数?
...以及您遇到的错误,您必须从
更正您的代码
Thread thread = new Thread(new ThreadStart(download(filename));
到
Thread thread = new Thread(new ThreadStart(download));
thread.Start(filename);
不过,这个问题看起来更复杂。
Thread 类当前 (4.7.2) 提供了几个 constructors 和一个 Start 重载方法。
这个问题的相关构造函数是:
public Thread(ThreadStart start);
和
public Thread(ParameterizedThreadStart start);
接受ThreadStart 代表或ParameterizedThreadStart 代表。
对应的代表如下:
public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);
因此可以看出,要使用的正确构造函数似乎是采用ParameterizedThreadStart 委托的构造函数,以便线程可以启动符合委托指定签名的某些方法。
实例化Thread 类的一个简单示例是
Thread thread = new Thread(new ParameterizedThreadStart(Work));
或者只是
Thread thread = new Thread(Work);
相应方法的签名(在本例中称为Work)如下所示:
private void Work(object data)
{
...
}
剩下的就是启动线程了。这是通过使用任一
public void Start();
或
public void Start(object parameter);
虽然Start() 会启动线程并将null 作为数据传递给方法,但Start(...) 可用于将任何东西 传递给线程的Work 方法。 p>
然而,这种方法存在一个大问题:
传入Work 方法的所有内容都被转换为一个对象。这意味着在 Work 方法中,它必须再次转换为原始类型,如下例所示:
public static void Main(string[] args)
{
Thread thread = new Thread(Work);
thread.Start("I've got some text");
Console.ReadLine();
}
private static void Work(object data)
{
string message = (string)data; // Wow, this is ugly
Console.WriteLine($"I, the thread write: {message}");
}
铸造是您通常不想做的事情。
如果有人传递了其他不是字符串的东西怎么办?因为一开始这似乎是不可能的(因为这是我的方法,我知道我在做什么或该方法是私有的,有人怎么能将任何东西传递给它?)由于各种原因,您可能最终会遇到这种情况。由于某些情况可能不是问题,因此其他情况是。在这种情况下,您最终可能会得到一个 InvalidCastException,您可能不会注意到它,因为它只是终止了线程。
作为一种解决方案,您希望获得一个通用的ParameterizedThreadStart 委托,例如ParameterizedThreadStart<T>,其中T 是您要传递给Work 方法的数据类型。不幸的是,这样的东西不存在(还没有?)。
然而,这个问题有一个suggested solution。它涉及创建一个类,该类包含要传递给线程的数据以及表示工作方法的方法,如下所示:
public class ThreadWithState
{
private string message;
public ThreadWithState(string message)
{
this.message = message;
}
public void Work()
{
Console.WriteLine($"I, the thread write: {this.message}");
}
}
使用这种方法,您可以像这样启动线程:
ThreadWithState tws = new ThreadWithState("I've got some text");
Thread thread = new Thread(tws.Work);
thread.Start();
因此,通过这种方式,您可以简单地避免强制转换,并以一种类型安全的方式向线程提供数据;-)