[英]Does .Net reuse the same thread over different requests?
I have the following class: 我有以下课程:
public static class ThreadStaticContainer
{
[ThreadStatic]
private static Dictionary<string, string> _valueDictionary;
public static Dictionary<string, string> ValueDictionary
{
get { return _valueDictionary ?? (_valueDictionary = new Dictionary<string, string>()); }
}
}
And it is called in my MVC Action like this: 它在我的MVC Action中被调用如下:
public ActionResult About()
{
ThreadStaticContainer.ValueDictionary.Add("1","1");
return View();
}
And every so often I get the exception: 我经常得到例外:
An item with the same key has already been added.
已添加具有相同键的项目。
Which surprises me because I thought that each request got a new thread. 这让我感到惊讶,因为我认为每个请求都有一个新线程。 But it's acting as if sometimes a request will reuse a thread.
但它的表现好像有时请求会重用一个线程。
What's going on? 这是怎么回事?
Threads are expensive. 线程很贵。
To avoid creating too many threads, ASP.Net handles requests on reusable threads from the ThreadPool. 为了避免创建太多线程,ASP.Net处理来自ThreadPool的可重用线程的请求。
Therefore, you cannot use [ThreadStatic]
like that. 因此,你不能像那样使用
[ThreadStatic]
。
Instead, you should store things in HttpContext.Items
. 相反,您应该将东西存储在
HttpContext.Items
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.