简体   繁体   中英

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:

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.
Therefore, you cannot use [ThreadStatic] like that.

Instead, you should store things in HttpContext.Items .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM