Using Parallel Extensions with ThreadStatic attribute. Could it leak memory?

不羁岁月 提交于 2019-12-04 05:19:06

I would strongly encourage using the normal pattern for thread-local storage, described in this MSDN article.

When you use [ThreadStatic], what matters is whether or not a threadpool thread cleans up the TLS variables when it terminates. There isn't any suggestion in the MSDN docs that it doesn't. It wouldn't be hard to implement, it only has to call the TlsFree() API function. I wrote a little test app, no evidence of any leak.

EDIT: Given Hans's answer, it sounds like the TLS actually would be cleaned up anyway... which just leaves this bit of the answer:

Do you really have no better way of reusing values within a thread? If there are two tasks which use the same thread (one completes, then the other runs) are they really going to want the same value? Are you actually just using this as a way of avoiding propagating the data in a more controlled way through your task?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!