【发布时间】:2012-04-30 03:24:29
【问题描述】:
我知道我可以通过调用 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 有关。
标签: c# multithreading