编辑:已回答的问题。通过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
TL; DR - 你为什么不只是调整访问修饰符所以它在类的外部访问? – 2015-04-02 13:09:39
将线程传递给TestClass的构造函数。 – Amy 2015-04-02 13:10:30
您可以将testThread从您的主类传递到其他类的runFunction方法。以此答案为例,http://stackoverflow.com/questions/3360555/how-to-pass-parameters-to-threadstart-method-in-thread – Shar1er80 2015-04-02 13:12:24