获取创建线程的模块/文件名?

时间:2013-07-25 16:01:48

标签: c# multithreading

我使用下面的代码来获取当前正在运行的进程中的线程列表。

Process p=Process.GetCurrentProcess();
var threads=p.Thread;

但我的要求是知道创建线程的文件名或模块名称。

请指导我达到我的要求。

1 个答案:

答案 0 :(得分:1)

我会找到文件名。它可以做到,但它可能不值得努力。而是将Name上的Thread属性设置为创建它的类的名称。

使用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());
  }
}
相关问题