Ohad Horesh
Ohad Horesh

Reputation: 4390

.NET Is there a way to get the parent thread id?

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.

Upvotes: 7

Views: 6045

Answers (4)

Wolfgang Grinfeld
Wolfgang Grinfeld

Reputation: 1008

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.

Upvotes: 0

Martin Liversage
Martin Liversage

Reputation: 106826

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.

Upvotes: 2

JSBach
JSBach

Reputation: 4747

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...

Upvotes: 0

Jan Jongboom
Jan Jongboom

Reputation: 27313

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

Upvotes: 11

Related Questions