sivaprakash
sivaprakash

Reputation: 79

Get the module/File name, where the thread was created?

I used the below code to get the list the threads in the currently running process.

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

But my requirement is to know the file name or the module name, where the thread is created.

Please guide me to achieve my requirements.

Upvotes: 2

Views: 774

Answers (1)

Brian Gideon
Brian Gideon

Reputation: 48949

I would punt on getting the file name. It can be done, but it is probably not worth the effort. Instead, set the Name property on the Thread to the name of the class that created it.

You will be able to see the Name value when inspected with the Visual Studio debugger. If you want to get a list of all managed threads in the current process via code then you will need to create your own thread repository. You cannot map a ProcessThread to a Thread because there is not always a one-to-one relationship between the two.

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); 
      }
    }
  }
}

And it would be used like this.

class SomeClass
{
  public void StartOperation()
  {
    string name = typeof(SomeClass).FullName;
    ThreadManager.StartNew(name, () => RunOperation());
  }
}

Update:

If you are using C# 5.0 or higher you can experiment with the new Caller Information attributes.

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());
  }
}

Upvotes: 1

Related Questions