Inheriting ThreadStatic values to implement dynamic scoping in C#/.NET in multithreaded context
Asked Answered
M

1

6

Is there a way to make newly-spawned threads inherit the values of ThreadStatic state (or something like it) on their parent threads? I would like to use this (or something like it) to implement "dynamically scoped" special variables that contain operation/task context information to use for tracking/logging, etc. Is this a reasonable approach, and can it be made to work?

Massasoit answered 21/1, 2010 at 1:58 Comment(0)
A
6

You can't "inherit" values. However, the new ThreadLocal<T> class for .NET 4 allows you to provide a Func<T> in the constructor, which can initialize the thread based on the parent's state. This would provide a reasonable workaround.

Allisonallissa answered 21/1, 2010 at 2:8 Comment(3)
Thanks, this is certainly interesting. But how would I allow the child to access the parent's state?Massasoit
You could use a lambda in the parent that provides access to the variable(s) in question that are required to initalize the ThreadLocal<T>. This uses a form of lazy initialization, so on first use, you'd get the current parent's state.Allisonallissa
this didn't do what I needed at the time for some reason I've forgotten, but it was nice to know about this anyway.Massasoit

© 2022 - 2024 — McMap. All rights reserved.