【问题标题】:Calling a thread from another class (C#)从另一个类调用线程 (C#)
【发布时间】: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


【解决方案1】:
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

【讨论】:

  • 这与我所追求的很接近;但我正在尝试检查我创建的与主线程并行运行的线程是否处于活动状态
  • 您的检查代码正在您要检查其运行状态的线程中运行。猜猜检查的结果是什么。
  • 我将在整个程序中运行多个线程,我需要确定其中一个是否正在运行,因为它们不会总是同时处于活动状态
  • 啊,我明白你从哪里来了。这更有意义!
猜你喜欢
  • 2019-07-11
  • 2012-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多