What are best practices for using thread local storage in .NET?

喜夏-厌秋 提交于 2019-12-04 04:06:21
csgero

A gotcha for asp.net applications: the processing of a single request might switch threads, namely if there are parallel requests in the same session. Because of this, anything you put in TLS before the HttpApplication.PostRequireRequestState event might not be there later, because you are on a different thread.

[Edit by the asker]

For my particular use case, I ended up adding a key-value pair to the SqlException.Data dictionary, which I then retrieve when I log the exception details. This gives me the functionality I was hoping to use thread local storage for.

Thread local storage is a quick way to fix a library that was designed before threads and uses a lot of global variables and statics. It's the way that the C standard library was made thread-safe while not changing its interface (internally, many functions use static buffers).

Generally, it's kind of good for that purpose. If you have to have global data in a multi-threaded environment, then thread-local storage is a good way to go. A common reason is that you are calling a third-party function that calls you back in the same stack-frame but doesn't give you a hook for passing extra information -- this happens a lot when you try to wrap older C libraries in .NET.

Have a look at new .net 4 ThreadLocal<T> class with an example, more info here.

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