C# CallContext 与 ThreadStatic

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/273301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:04:11  来源:igfitidea点击:

CallContext vs ThreadStatic

c#asp.net

提问by Cristian Libardo

What are differences between CallContext and ThreadStatic?

CallContext 和 ThreadStatic 之间有什么区别?

I've understood that in an ASP.NET environment data stored in CallContext could be persisted throughout the request until it ends while ThreadStatic may or may not work since the request may switch threads. I've also learned that the HttpContext is internally stored using the CallContext.

我已经明白,在 ASP.NET 环境中,存储在 CallContext 中的数据可以在整个请求中持续存在,直到它结束,而 ThreadStatic 可能会或可能不会工作,因为请求可能会切换线程。我还了解到 HttpContext 是使用 CallContext 内部存储的。

In a regular application they both seem to persist throughout the same thread call. When isn't this the case?

在常规应用程序中,它们似乎都在同一个线程调用中持续存在。什么时候不是这样?



Edit:In the comments I learned that the call context is an abstraction over a thread static store. The ASP.NET framework explicitly moves the data from one thread to the next that is to handle one request. Other framework that wants to provide thread agility could do the same to for contextual storage.

编辑:在评论中我了解到调用上下文是对线程静态存储的抽象。ASP.NET 框架显式地将数据从一个线程移动到下一个处理一个请求的线程。其他想要提供线程敏捷性的框架可以为上下文存储做同样的事情。

采纳答案by Jon Skeet

Very often a request will use the same thread throughout, but it certainly won't always be the case - ASP.NET exhibits thread agility. There's an old in-depth blog article about the matterfrom 2005, but as of .NET 4.5 things are rather better.

一个请求经常会在整个过程中使用相同的线程,但肯定不会总是这样 - ASP.NET 表现出线程敏捷性。2005 年有一篇关于此事的旧深入博客文章,但从 .NET 4.5 开始,情况好多了

回答by Martin Brown

Items stored as ThreadStatic are available to more than one request. IIS reuses the thread after a request is complete to process subsequent requests, it can even swap a request from one thread to another during processing. ASP.Net clears down the CallContext after each request.

存储为 ThreadStatic 的项目可用于多个请求。IIS 在请求完成后重用线程来处理后续请求,它甚至可以在处理过程中将请求从一个线程交换到另一个线程。ASP.Net 在每次请求后清除 CallContext。