A while ago I raised a question in the newgroups about Static functions and how is it that they can be thread safe, a look through the C# language specifications (mspress book and w3c), various mspress programming, wrox books, msdn, a bit of a google, shed no light on the situation.

This is quite a big deal if you are writing web sites as whilst you may be coding single threaded you are by the very nature of web writing multi-threaded apps, you should be aware of this stuff.

I thought well ok you have this Static method with parameters or local variable store, and you can also have class level static variables. In all the examples It shows how to lock the Static class so that the class level static is safe, so how is it the parameters are safe ? They must be in the .NET equivalent of thread local store (something I remembered from vb6 com days). But now where could I find out if this was the case.

Well I raised a call with MS and it is.

Basically all parameters and local variables are stored on the stack, or pointers to variables on the heap are stored in the stack, as each thread running maintains its own stack the parameters and local store are hidden from each other.

Another great thing is that this applies to databases so long as the database connection/adaptor/set etc are also thread local to the static method.

Another piece of info that was voluteered from MS was an attribute you can “attach” to a static variable.

static int value;

This has the effect of making this static variable local per thread, which would be quite useful in writing the c# equivalent of global functions.


This makes an insteresting point about why not to use the attribute, in certain circumstances.