继承 ThreadStatic 值以在多线程上下文中的 C#/.NET 中实现动态作用域
有没有办法让新生成的线程继承其父线程上的 ThreadStatic 状态(或类似的状态)的值?我想使用它(或类似的东西)来实现“动态范围”特殊变量,其中包含用于跟踪/日志记录等的操作/任务上下文信息。这是一种合理的方法吗?它可以工作吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能“继承”价值观。但是,新的
ThreadLocal
.NET 4 的类 允许您在 构造函数,它可以根据父级的状态初始化线程。这将提供一个合理的解决方法。You can't "inherit" values. However, the new
ThreadLocal<T>
class for .NET 4 allows you to provide aFunc<T>
in the constructor, which can initialize the thread based on the parent's state. This would provide a reasonable workaround.