2012-04-30 46 views
1

我知道我可以通過調用Thread.CurrentThread.Name來獲取線程名稱從內部對象方法獲取線程名稱

但我有一個棘手的情況。

我創建了兩個線程,每個線程啓動一個新對象(稱爲objA)並運行一個方法。 (objA)方法(objAM),我創建另一個對象(說objB)並運行一個方法(OBJBM)。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 


namespace ConsoleApplication1 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      TESTA a = new TESTA(); 
     } 

    } 

    class TESTA 
    { 
     private Thread t; 

     public TESTA() 
     { 
      t = new Thread(StartThread); 
      t.Name = "ABC"; 
      t.IsBackground = true; 
      t.Start(); 

      t = new Thread(StartThread); 
      t.Name = "XYZ"; 
      t.IsBackground = true; 
      t.Start(); 

     } 

     private void StartThread() 
     { 
      objA thisA = new objA(); 
     } 
    } 

    class objA 
    { 
     private System.Threading.Timer t1; 

     public objA() 
     { 
      objAM(); 
      t1 = new Timer(new TimerCallback(testthread), null, 0, 1000); 
     } 

     private void objAM() 
     { 
      Console.WriteLine("ObjA:" + Thread.CurrentThread.Name); 
     } 

     private void testthread(object obj) 
     { 
      objB thisB = new objB(); 
     } 
    } 

    class objB 
    { 
     public objB() 
     { 
      objBM(); 
     } 

     private void objBM() 
     { 
      Console.WriteLine("ObjB:" + Thread.CurrentThread.Name); 
     } 
    } 
} 

但objB中的Thread.CurrentThread.Name的值返回空。

如何獲得objBM中的線程名稱?

+0

您提供的代碼示例未編譯。如果你需要幫助,你可以考慮提供一個簡短的完整程序來編譯和說明錯誤。 –

+0

已更新。我想它是否與threading.timer相關,而不是timer.timer被使用。 – AlphaAu

回答

2

從描述System.Threading.Timer:方法不會在創建定時器的線程上執行;它在系統提供的ThreadPool線程上執行。

因此您的testthread方法在未命名的ThreadPool線程上執行。順便說一句,你可以通過調用Thread.CurrentThread.IsThreadPoolThread來驗證它。

+0

非常感謝。我忽略了線程屬性。 – AlphaAu

+0

@AlphaAu你爲什麼不接受這個答案? –

+0

似乎我不小心錯誤地點擊該頁面,當我重新訪問此線程... – AlphaAu