Ev.
Ev.

Reputation: 7589

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?

Upvotes: 0

Views: 732

Answers (1)

SLaks
SLaks

Reputation: 887305

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.

Upvotes: 2

Related Questions