2015-04-02 33 views
0

编辑:已回答的问题。通过Igor完美解释答案。 (谢谢!)调用另一个类的线程(C#)

问题:如何在同一程序中访问/控制另一个类的线程? 我将有多个线程活动(不是一次全部),我需要检查一个是否活动(这不是主线程)。

我在C#中编程,我尝试使用线程。 我有2个类,我的线程在主类中调用另一个类中的函数。在我的其他班级,我想看看“thread.isAlive == true”,但我认为它不公开。我不知道可以使用另一个类的线程的语法/代码?我努力让它工作。

我可以调用其他类,但我不能调用类之间的线程。 (不能声明线程类外) 抛出的错误是:

Error 1 The name 'testThread' does not exist in the current context 

示例代码:

//Headers 
using System.Threading; 
using System.Threading.Tasks; 
namespace testProgram 
{ 
    public class Form1 : Form 
    { 
     public void main() 
     { 
      //Create thread referencing other class 
      TestClass test = new TestClass(); 
      Thread testThread = new Thread(test.runFunction) 
      //Start the thread 
      testThread.Start(); 
     }//Main End 
    }//Form1 Class End 
    public class TestClass 
    { 
     public void runFunction() 
     { 
      //Check if the thread is active 
      //This is what I'm struggling with 
      if (testThread.isAlive == true) 
      { 
       //Do things 
      }//If End 
     }//runFunction End 
    }//testClass End 
}//Namespace End 

感谢您的阅读! -Dave

+2

TL; DR - 你为什么不只是调整访问修饰符所以它在类的外部访问? – 2015-04-02 13:09:39

+1

将线程传递给TestClass的构造函数。 – Amy 2015-04-02 13:10:30

+1

您可以将testThread从您的主类传递到其他类的runFunction方法。以此答案为例,http://stackoverflow.com/questions/3360555/how-to-pass-parameters-to-threadstart-method-in-thread – Shar1er80 2015-04-02 13:12:24

回答

5
if (System.Threading.Thread.CurrentThread.isAlive == true) { ... } 

但是,你这样做是:“是单线程的,在我执行的,运行是它正在运行,因为这是做检查的代码是在它,我现在在那?码。”

但如果你坚持:

public class Form1 : Form 
{ 
    public void main() 
    { 
     //Create thread referencing other class 
     TestClass test = new TestClass(); 
     Thread testThread = new Thread(test.runFunction) 
     test.TestThread = testThread; 
     //Start the thread 
     testThread.Start(); 
    }//Main End 
}//Form1 Class End 
public class TestClass 
{ 
    public Thread TestThread { get; set; } 
    public void runFunction() 
    { 
     //Check if the thread is active 
     if (TestThread != null && TestThread.isAlive == true) 
     { 
      //Do things 
     }//If End 
    }//runFunction End 
}//testClass End 
+0

这与我所追求的接近;但我试图检查一个我创建的线程是否与主线程并行运行 – Hughsie28 2015-04-02 13:17:53

+0

您的检查代码正在您尝试检查的运行状态的线程中运行。猜猜检查结果会是什么。 – Igor 2015-04-02 13:20:06

+0

我将在完整程序中运行多个线程,并且我需要确定它们中的一个是否正在运行,因为它们不会一直处于活动状态 – Hughsie28 2015-04-02 13:21:25