ThreadStatic 对象的确定性处置

发布于 2024-07-05 18:15:06 字数 629 浏览 6 评论 0原文

ThreadStatic 属性 将静态变量声明为每个线程唯一的。 您知道正确处理此类变量的简单模式吗?

我们之前使用ThreadStatic的是ThreadContextManager。 每个线程都分配有一个 ThreadContext,它保留所有特定于线程的信息。 我们生成了一些线程并让它们工作。 然后,当它们全部完成后,我们处置 ThreadContentManager,如果它们是 IDisposable,那么 ThreadContentManager 又处置所有上下文。

我没有看到将此模式转换为 ThreadStatic 对象的直接方法。 这些对象最终将被丢弃,因为线程死亡,因此没有任何东西引用它们。 然而,只要有可能,我们更喜欢确定性处置。

更新

我并不真正直接控制线程 - 我正在使用 Microsoft CCR,它有一个执行任务的 ThreadPool。 当所有任务完成后,我将处理调度程序(它保存线程池)。 问题是 - 我没有机会“在线程主函数结束时”做任何事情 - 所以我无法在线程运行结束时手动处理事情。 我可以以某种方式从线程外部访问线程的静态对象吗?

The ThreadStatic attribute declares a static variable as unique-per-thread.
Do you know an easy pattern to correctly dispose such variables?

What we used before ThreadStatic is a ThreadContextManager. Every thread was allocated a ThreadContext which retained all thread-specific information. We spawned some threads and let them work. Then, when they all finished, we disposed of the ThreadContentManager, which in turn disposed all the contexts if they were IDisposable.

I don't see an immediate way to translate this pattern to ThreadStatic objects. The objects will be disposed of eventualy, because the threads die, and so nothing reference them. However, we prefer deterministic dispose whenever possible.

Update

I do not really control the threads directly - I'm using Microsoft CCR, which has a ThreadPool that does tasks. When all the tasks are done, I'm disposing the Dispatcher (which holds the threadpool). The thing is - I do not get a chance to do anything "at the end of a thread's main function" - so I can't dispose things manually at the end of a thread's run. Can I access the thread's static objects from outside the thread somehow?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事和酒 2024-07-12 18:15:06

您仍然可以使用 ThreadContextManager 类的等效项来处理处置。 生成的线程会处理这个“管理器”对象,而该对象又会取出它所知道的所有其他线程静态对象。

我更喜欢拥有相对较少的线程静态对象并使用上下文对象。 这使得线程特定状态仅保留在少数位置,并使此类模式变得更容易。

更新:要处理线程池情况,您可以创建一个基本“任务”对象,该对象是您传递给线程池的对象。 它可以执行代码所需的任何通用初始化,调用“真实”任务,然后执行所需的任何清理。

You can still use the equivalent of your ThreadContextManager class to handle the dispose. The spawned threads dispose of this 'manager' object which in turn takes out all the other thread static objects it knows about.

I prefer to have relatively few thread static objects and use a context object instead. This keeps the thread specific state in only a few places, and makes patterns like this easier.

Update: to handle the threadpool case you could create a base 'task' object that is the one that you pass to the thread pool. It can perform any generic initialization your code needs, invoke the 'real' task and then performs any cleanup needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文