简体   繁体   English

.Net是否在不同的请求中重用相同的线程?

[英]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.

相关问题 .NET 是否在新的不同线程池线程上恢复等待继续,还是重用先前恢复的线程? - Does .NET resume an await continuation on a new different thread pool thread or reuse the thread from a previous resumption? 有没有办法重用同一个线程? - Is there a way to reuse the same thread? 重用线程以执行不同的操作 - Reuse thread for different action .NET Core 如何同时处理不同的请求? - How does .NET Core handle separate requests at the same time? 在.NET中,System.Threading.Thread.CurrentPrincipal对于不同的线程是相同的 - In .NET, System.Threading.Thread.CurrentPrincipal is the same for different threads SemaphoreSlim(.NET)是否阻止同一线程进入块? - Does SemaphoreSlim (.NET) prevent same thread from entering block? 如何重用相同的变量,但用于不同的类型? - How to reuse the same variable, but for different types? 当线程已经终止(.NET 5 / Core)时,Thread.Join 方法并不总是返回相同的值 - Thread.Join method does not always return the same value when the thread has already terminated (.NET 5 / Core) 我可以为不同的部分重复使用具有相同值的相同单选按钮吗? - Can I reuse the same radiobutton with same value for different section? System.Threading.Thread在.NET Core中的含义与在.NET Framework中的含义相同吗? - Does System.Threading.Thread means same in .NET Core as in .NET Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM