开发者

Associate data with a thread: How do you do that?

开发者_开发知识库While writing some aysnc controllers in ASP.NET MVC2, I ran up against a situation where I had to call AsyncManager.Sync. It got me wondering:

When I retrieve HttpContext.Current, what's going on? How does ASP.NET know which HttpContext I'm after? How is the current context associated with this thread, and how is it retrieved?


Thread scoped storage is used, this is called Thread Local Storage.

This mechanism allows data to be affinitized with a thread i.e. only the thread that allocates the data sees the data. This is useful for creating so called ambient programming models such as HttpContext.Current and TransactionScope. The mechanism allows data to be accessible at any time on the executing thread without having to "tramp" data through method parameters for instance. It's an elegant solution for certain context\orthogonal problems.

There are number of ways of using TLS including the ThreadStaticAttribute and Thread.SetData\GetData.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜