2015-04-02 153 views
0

編輯:已回答的問題。通過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

+2

TL; DR - 你爲什麼不只是調整訪問修飾符所以它在類的外部訪問? – 2015-04-02 13:09:39

+1

將線程傳遞給TestClass的構造函數。 – Amy 2015-04-02 13:10:30

+1

您可以將testThread從您的主類傳遞到其他類的runFunction方法。以此答案爲例,http://stackoverflow.com/questions/3360555/how-to-pass-parameters-to-threadstart-method-in-thread – Shar1er80 2015-04-02 13:12:24

回答

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 
+0

這與我所追求的接近;但我試圖檢查一個我創建的線程是否與主線程並行運行 – Hughsie28 2015-04-02 13:17:53

+0

您的檢查代碼正在您嘗試檢查的運行狀態的線程中運行。猜猜檢查結果會是什麼。 – Igor 2015-04-02 13:20:06

+0

我將在完整程序中運行多個線程,並且我需要確定它們中的一個是否正在運行,因爲它們不會一直處於活動狀態 – Hughsie28 2015-04-02 13:21:25