7

Suppose the main thread is spawning a new thread t1, how can my code that runs on t1 find the thread id of the main thread (using c#)?

Edit:
I don't control the creation of the new thread. So I can't pass any parameters to the thread.

Thanks.

Ohad Horesh
  • 4,340
  • 6
  • 28
  • 45
  • 2
    Fundamentally all threads in a process under Win32 are equal, there is no "main thread". .NET adds the refinement of background threads, but there is still no "main thread". – Richard Nov 18 '10 at 12:21

4 Answers4

11

You can't.

Yet you might consider:

  1. Prefix the name of the new thread with the thread ID from the parent thread
  2. Create a constructor on the method you want to spawn that requires the thread ID from the parent
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120
2

If you only have two threads and the second thread is a background thread you can enumerate all threads in the process and eliminate the background thread by reading the Thread.IsBackground property. Not very pretty but perhaps what you need?

You can read more about foreground and background threads on MSDN.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
0

I don't know if you have a property to do that, but you could add a new parameter to your thread an pass to it. It would be the easiest way I could think of...

JSBach
  • 4,679
  • 8
  • 51
  • 98
0

If you are using a Threadpool (thus no control over the creation of Threads here) you could work as follows:

private static void myfunc(string arg)
{
    Console.WriteLine("Thread "
                     + Thread.CurrentThread.ManagedThreadId
                     + " with parent " + Thread.GetData(Thread.GetNamedDataSlot("ParentThreadId")).ToString()
                     + ", with argument: " 
                     + arg
                     );
}
public static int Main(string[] args)
{
    var parentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
    WaitCallback waitCallback = (object pp) =>
    {
        Thread.SetData(Thread.GetNamedDataSlot("ParentThreadId"), parentThreadId);
        myfunc(pp.ToString());
    };

    ThreadPool.QueueUserWorkItem(waitCallback, "my actual thread argument");
    Thread.Sleep(1000);
    return 0;
}

This would produce something like:

 Thread 3 with parent 1, with argument: my actual thread argument

If however there is no way to pass data to the child thread at all, consider renaming the parent thread, or alternatively all the child threads.

Wolfgang Grinfeld
  • 870
  • 10
  • 11