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

标签 c# multithreading

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

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/

相关文章:

c# - 如何在事件处理程序中设置计时器?

c# - C# 是否可以在静态函数内调用非静态函数?

c# - 在 C# 中读取数据集

java - 这里有什么遗漏/错误?

java - 共享进程/线程

线程和图形用户界面应用程序之间的 Python 新样式信号和槽

c# - 来自文本文件变量的 csproj 文件中的多个提示路径

c# - 使用代码从 ViewModel 绑定(bind)控件中检索 System.ComponentModel.DataAnnotations.DisplayAttribute 属性

c++ - 我如何在 C++ 中实现线程关联

java - 为对象定义线程 ID 并中断