我正在尝试通过以下方式传递参数:
Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));
知道怎么做吗?我会很感激一些帮助
我正在尝试通过以下方式传递参数:
Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));
知道怎么做吗?我会很感激一些帮助
懒惰的别列佐夫斯基有正确的答案。我想指出,由于变量捕获,从技术上讲,您可以使用 lambda 表达式传递任意数量的参数:
var thread = new Thread(
() => DoMethod(a, b, c));
thread.Start();
这是一种调用不适合ThreadStart
orParameterizedThreadStart
委托的方法的便捷方式,但请注意,如果在将父线程中的参数传递给子线程的代码后更改它们,则很容易导致数据竞争。
使用接受对象的重载Thread.Start
方法(如果需要多个参数,可以传递自定义类型或数组):
Foo parameter = // get parameter value
Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));
thread.Start(parameter);
并DoMethod
简单地将参数转换为您的参数类型:
private void DoMethod(object obj)
{
Foo parameter = (Foo)obj;
// ...
}
顺便说一句,在 .NET 4.0 及更高版本中,您可以使用任务(还要小心竞争条件):
Task.Factory.StartNew(() => DoMethod(a, b, c));
您可以使用匿名类型,而不是像@user1958681 那样创建一个传递多个参数的类,然后只需使用动态类型来提取您的参数。
class MainClass
{
int A = 1;
string B = "Test";
Thread ActionThread = new Thread(new ParameterizedThreadStart(DoWork));
ActionThread.Start(new { A, B});
}
然后在 DoWork
private static void DoWork(object parameters)
{
dynamic d = parameters;
int a = d.A;
string b = d.B;
}
另一种归档您想要的内容的方法是在您的函数/方法中返回一个委托。举个例子:
class App
{
public static void Main()
{
Thread t = new Thread(DoWork(a, b));
t.Start();
if (t.IsAlive)
{
t.IsBackground = true;
}
}
private static ThreadStart DoWork(int a, int b)
{
return () => { /*DoWork*/ var c = a + b; };
}
}
new Thread(() => { DoMethod(a, b, c); }).Start();
或者
new Thread(() => DoMethod(a, b, c)).Start();
// Parameters to pass to ParameterizedThreadStart delegate
// - in this example, it's an Int32 and a String:
class MyParams
{
public int A { get; set; }
public string B { get; set; }
// Constructor
public MyParams(int someInt, string someString)
{
A = someInt;
B = someString;
}
}
class MainClass
{
MyParams ap = new MyParams(10, "Hello!");
Thread t = new Thread(new ParameterizedThreadStart(DoMethod));
t.Start(ap); // Pass parameters when starting the thread
}
class Program
{
public static void Main()
{
MyClass myClass = new MyClass();
ParameterizedThreadStart pts = myClass.DoMethod;
Thread thread1 = new Thread(pts);
thread1.Start(20); // Pass the parameter
Console.Read();
}
}
class MyClass
{
private int Countdown { get; set; }
public void DoMethod(object countdown) // Parameter must be an object and method must be void
{
Countdown = (int) countdown;
for (int i = Countdown; i > 0; i--)
{
Console.WriteLine("{0}", i);
}
Console.WriteLine("Finished!");
}
}