从另一个类调用一个线程(C#)

时间:2015-04-02 13:08:45

标签: c# multithreading class

编辑:问题已解答。答案由 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

感谢阅读! -Dave

1 个答案:

答案 0 :(得分: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