.NET Framework thread "ancestry"

I am looking for a way to define for a thread on which another thread was originally spawned. I don't know if there is a mechanism for this, similar to the Parent property in Tasks in the new Parallel Task Library for .NET 4

Edit: Further research actually seems to indicate that there is no place to store this information, so there are very few ugly hacks, this seems to be impossible to implement transparently.

As such, I think I'll accept the example code below as the most possible (opaque) answer to solve the problem, although I'll have to look for an alternative design. Thanks:)

+1


a source to share


2 answers


The system does not provide this functionality internally. You can easily pass the thread id of the parent thread to the thread start function:



static class ThreadSpawner
{
    [ThreadStatic]
    private static int parentThreadId;
    public static int ParentThreadId
    {
        get { return parentThreadId; }
    }

    private class ThreadInfo
    {
        public int ParentId;
        public Action Method;
    }

    private static void StartThread(object parameter)
    {
        var threadInfo = (ThreadInfo)parameter;
        parentThreadId = threadInfo.ParentId;
        threadInfo.Method();
    }

    public static void Spawn(Action start)
    {
        new Thread(StartThread).Start(
            new ThreadInfo { 
                 Method = start, 
                 ParentId = Thread.CurrentThread.ManagedThreadId 
            });
    }
}


// Usage:
ThreadSpawner.Spawn(MyMethod);

static void MyMethod() { 
    Console.WriteLine(ThreadSpawner.ParentThreadId);
}

      

+2


a source


Even worse, creating a .NET thread does not guarantee that you will get your own thread, so you cannot depend on whether you can track the parent information of the thread using P / Invoke.

I know that if you write test code you will see your own stream, but you don't have to generate it, and under some conditions that are hard to guess, it won't.



EDIT: Can't get parent thread via P / Invoke.

+2


a source







All Articles