我使用下面的代码来获取当前正在运行的进程中的线程列表。获取创建线程的模块/文件名?
Process p=Process.GetCurrentProcess();
var threads=p.Thread;
但我的要求是知道创建线程的文件名或模块名称。
请指导我达到我的要求。
我使用下面的代码来获取当前正在运行的进程中的线程列表。获取创建线程的模块/文件名?
Process p=Process.GetCurrentProcess();
var threads=p.Thread;
但我的要求是知道创建线程的文件名或模块名称。
请指导我达到我的要求。
我打赌得到的文件名。它可以完成,但它可能不值得付出努力。相反,将Thread
上的Name
属性设置为创建它的类的名称。
当与Visual Studio调试器检查你将能够看到Name
值。如果你想通过代码获得当前进程中所有托管线程的列表,那么你将需要创建自己的线程库。您不能将ProcessThread
映射到Thread
,因为两者之间并不总是一对一的关系。
public static class ThreadManager
{
private List<Thread> threads = new List<Thread>();
public static Thread StartNew(string name, Action action)
{
var thread = new Thread(
() =>
{
lock (threads)
{
threads.Add(Thread.CurrentThread);
}
try
{
action();
}
finally
{
lock (threads)
{
threads.Remove(Thread.CurrentThread);
}
}
});
thread.Name = name;
thread.Start();
}
public static IEnumerable<Thread> ActiveThreads
{
get
{
lock (threads)
{
return new List<Thread>(threads);
}
}
}
}
它会像这样使用。
class SomeClass
{
public void StartOperation()
{
string name = typeof(SomeClass).FullName;
ThreadManager.StartNew(name,() => RunOperation());
}
}
更新:
如果您正在使用C#5.0或更高版本,你可以用新的Caller Information属性实验。
class Program
{
public static void Main()
{
DoSomething();
}
private static void DoSomething()
{
GetCallerInformation();
}
private static void GetCallerInformation(
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Console.WriteLine("Member Name: " + memberName);
Console.WriteLine("File: " + sourceFilePath);
Console.WriteLine("Line Number: " + sourceLineNumber.ToString());
}
}
我正在使用下面的代码来获取进程线程的详细信息,Process p = Process.GetCurrentProcess(); var thread = p.Thread; – sivaprakash
我们可以使用上述方法获取线程的堆栈跟踪吗? – sivaprakash
@sivaprakash:不,你不能使用纯粹的托管代码。 –
到目前为止,你是怎么试试?无论如何,你无法获得世界卫生组织创建的线程,你拥有的是它当前的堆栈跟踪(如果你确定它们保持在同一个程序集中,最大可以调用第一个函数)。 –
我认为它只关乎'过程',而不是'线程'。每个进程都附带一些'Modules'。你可以通过'Process'的'Modules'属性来访问它们。 –
我需要知道函数名称或模块名称,每个线程的创建位置。 – sivaprakash