2012-07-24 115 views
1

我需要解析一个对象到另一个对象。我知道我必须把c传给t1。如何做到这一点c#多线程,传递对象到另一个对象

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

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

参数化的ThreadStart – 2012-07-24 22:28:49

+2

糟糕,这个对象也在线程之外使用吗?那么你必须锁定它! – 2012-07-24 22:32:34

+0

跟进:如果你有你正在寻找的答案,不要忘记标记为正确。问候。 – 2012-07-28 05:34:08

回答

3

好吧,大家都缺少对象在线程外使用的点。这样,它必须同步以避免跨线程异常。

所以,解决办法是这样的:

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

希望这有助于。

Regards

+0

对我来说,问题更多的是关于对象到新线程的实际传递,但是您提出了一个很有用的观点。 +1 – 2012-07-24 23:03:22

+0

有点解释=)请注意,OP使用该对象作为停止线程的标志。 +1代码,以及 – 2012-07-24 23:07:36

3

你可以简单地做:

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

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

MSDN:ParameterizedThreadStart Delegate


甚至更​​好:

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

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

这种方法允许多个参数,并没有t要求您将对象转换为所需的类/结构。

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; 
} 
相关问题