我知道我可以通過調用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中的線程名稱?
您提供的代碼示例未編譯。如果你需要幫助,你可以考慮提供一個簡短的完整程序來編譯和說明錯誤。 –
已更新。我想它是否與threading.timer相關,而不是timer.timer被使用。 – AlphaAu