2

我需要将一个对象传递给另一个对象。我知道我必须传递ct1. 我该怎么做呢

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

private static void t1(Class1 c)
{
    while (c.process_done == false)
    {
        Console.Write(".");
        Thread.Sleep(1000);
    }
}
4

3 回答 3

4

你可以简单地做:

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

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

于 2012-07-24T22:33:48.660 回答
4

好的,每个人都错过了在线程外使用对象的要点。这样,必须同步,避免跨线程异常。

因此,解决方案将是这样的:

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

希望这可以帮助。

问候

于 2012-07-24T22:52:05.470 回答
2
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;
}
于 2012-07-24T22:35:34.293 回答