Hug*_*e28 0 c# multithreading class
编辑:问题回答.伊戈尔完美地解释了答案.(谢谢!)
问题:如何从同一程序中的另一个类访问/控制线程?我将激活多个线程(不是一次全部),我需要检查一个是否处于活动状态(这不是主线程).
我正在用C#编程,我正在尝试使用线程.我有2个类,我的线程在主类中启动,在另一个类中调用一个函数.在我的其他课程中,我想看看"thread.isAlive == true",但我认为它不公开.我不知道能够使用来自另一个类的线程的语法/代码?我很难让它发挥作用.
我可以调用另一个类,但我不能在类之间调用线程.(不能在类之外声明一个线程)抛出的错误是:
Error 1 The name 'testThread' does not exist in the current context
Run Code Online (Sandbox Code Playgroud)
示例代码:
//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
Run Code Online (Sandbox Code Playgroud)
谢谢阅读!戴夫
if (System.Threading.Thread.CurrentThread.isAlive == true) { ... }
Run Code Online (Sandbox Code Playgroud)
但是你这样做:"我正在执行的线程是否正在运行?是的,它正在运行,因为正在进行检查的代码在其中并且我当前在该代码中."
但如果你坚持:
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
Run Code Online (Sandbox Code Playgroud)