1

what is the meaning of [ThreadStatic()]

i got a piece of code and i found [ThreadStatic()] is used there what does it mean....when to use [ThreadStatic()]

public class Context
{
[ThreadStatic()]
private static Context _Context = null;

private HttpContext _HttpContext = null;

public Context()
{
    _HttpContext = HttpContext.Current;
}

public static Context Current
{
    if(_Context == null || 
       _HttpContext != _HttpContext.Current)
    {
        _Context = new Context();
    }
    return _Context;
}
}
Thomas
  • 33,544
  • 126
  • 357
  • 626

2 Answers2

2

From the documentation:

Indicates that the value of a static field is unique for each thread.

In your code _Context is static, but it is different for each thread.

If you have a background in more native programming, think of these as a semi-equivalent of Thread Local Storage.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • 1
    I don't think the points about asp.net are entirely accurate. A thread can be reused between requests so storing per request data in thread local isn't 100% safe. There are easier and safer ways of storing information per request. – James Gaunt Aug 25 '11 at 19:47
  • @James - Thanks - you are correct, threads are re-used; but 1 thread is never handling more than one request at a time since it just draws them from the thread pool. I removed the sentence to avoid any ambiguity. – vcsjones Aug 25 '11 at 19:50
2

From MSDN:

Indicates that the value of a static field is unique for each thread.

Read these:

Community
  • 1
  • 1