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

后端 未结 4 1263
一向
一向 2020-12-03 15:57

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

相关标签:
4条回答
  • 2020-12-03 16:18

    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.

    0 讨论(0)
  • 2020-12-03 16:29

    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.

    0 讨论(0)
  • 2020-12-03 16:29

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

    0 讨论(0)
  • 2020-12-03 16:39

    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
    0 讨论(0)
提交回复
热议问题