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

后端 未结 4 1278
一向
一向 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.

提交回复
热议问题