【发布时间】:2015-06-07 10:59:33
【问题描述】:
编辑:问题已回答。 Igor 完美解释了答案。 (谢谢!)
问题:如何从同一程序中的另一个类访问/控制线程? 我将有多个线程处于活动状态(不是一次全部),我需要检查一个是否处于活动状态(这不是主线程)。
我正在使用 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
感谢阅读! -戴夫
【问题讨论】:
-
TL;DR -- 你为什么不直接调整访问修饰符,让它可以在课堂外访问?
-
将线程传递给
TestClass的构造函数。 -
您可以将 testThread 从您的主类传递给其他类的 runFunction 方法。以这个 SO 答案为例,stackoverflow.com/questions/3360555/…
-
您的意思是 Thread.IsAlive 属性吗?如果您在 runFunction 中,我认为这将总是正确。我不明白线程如何询问自己是否还活着。
标签: c# multithreading class