C# 多线程;将对象传递给另一个对象

C# 多线程;将对象传递给另一个对象,c#,multithreading,C#,Multithreading,我需要将一个对象传递给另一个对象。我知道我必须通过c到t1。我该怎么做 Thread t = new Thread(t1); t.Start(); private static void t1(Class1 c) { while (c.process_done == false) { Console.Write("."); Thread.Sleep(1000); } } 你可以简单地做: Thread t = new Thread(ne

我需要将一个对象传递给另一个对象。我知道我必须通过
c
t1
。我该怎么做

Thread t = new Thread(t1);
t.Start();

private static void t1(Class1 c)
{
    while (c.process_done == false)
    {
        Console.Write(".");
        Thread.Sleep(1000);
    }
}
你可以简单地做:

Thread t = new Thread(new ParameterizedThreadStart(t1));
t.Start(new Class1());

public static void t1(object c)
{
  Class1 class1 = (Class1)c;
  ...
}
MSDN:


或者更好:

Thread thread = new Thread(() => t1(new Class1()));

public static void t1(Class1 c)
{
  // no need to cast the object here.
  ...
}

这种方法允许多个参数,并且不需要将对象强制转换为所需的类/结构。

好了,伙计们,每个人都忽略了对象在线程外使用的要点。这样,它必须同步以避免跨线程异常

private static void DoSomething()
{
    Class1 whatYouWant = new Class1();
    Thread thread = new Thread(DoSomethingAsync);
    thread.Start(whatYouWant);
}

private static void DoSomethingAsync(object parameter)
{
    Class1 whatYouWant = parameter as Class1;
}
因此,解决方案如下:

//This is your MAIN thread
Thread t = new Thread(new ParameterizedThreadStart(t1));
t.Start(new Class1());
//...
lock(c)
{
  c.magic_is_done = true;
}
//...

public static void t1(Class1 c)
{
  //this is your SECOND thread
  bool stop = false;
  do
  {
    Console.Write(".");
    Thread.Sleep(1000);

    lock(c)
    {
      stop = c.magic_is_done;
    }
    while(!stop)
  }
}
希望这有帮助


关于

Oops,这个对象也在线程外使用?那你得把它锁上!跟进:如果你得到了你正在寻找的答案,别忘了标记为正确。对我来说,问题更多的是关于对象到新线程的实际传递,但是你提出了一个非常有效的观点+1A一点解释=)注意OP使用对象作为停止线程的标志+1作为您的代码