通过ParameterizedThreadStart传递参数

时间:2012-12-08 11:02:19

标签: c# multithreading

我正在尝试通过以下方式传递参数:

Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));

知道怎么做吗?我很感激一些帮助

7 个答案:

答案 0 :(得分:89)

lazyberezovsky有正确的答案。我想要注意,从技术上讲,由于变量捕获,你可以使用lambda表达式传递任意数量的参数:

var thread = new Thread(
       () => DoMethod(a, b, c));
thread.Start();

这是调用不适合ThreadStartParameterizedThreadStart委托的方法的一种方便方法,但是如果更改父线程中的参数,请注意很容易导致数据争用将它们传递给子线程的代码之后。

答案 1 :(得分:33)

使用重载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及更高版本中

BTW ,您可以使用任务(也要注意竞争条件):

Task.Factory.StartNew(() => DoMethod(a, b, c));

答案 2 :(得分:1)

另一种归档所需内容的方法是在函数/方法中返回一个委托。请看以下示例:

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; };
  }

}

答案 3 :(得分:1)

new Thread(() => { DoMethod(a, b, c); }).Start();

new Thread(() => DoMethod(a, b, c)).Start();

答案 4 :(得分:0)

// 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
}

答案 5 :(得分:0)

不是像@ 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 = parameters.A;
    string b = parameters.B;
 }

答案 6 :(得分:0)

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!");
  }
}