我使用下面的代码来获取当前正在运行的进程中的线程列表。
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());
}
}
关于c# - 获取创建线程的模块/文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17863139/