Does a static method share its local variables & what happens during concurrent usage from different threads? Does a static method share its local variables & what happens during concurrent usage from different threads? multithreading multithreading

Does a static method share its local variables & what happens during concurrent usage from different threads?


Local variables within the method live on the stack and each thread has its own stack. Therefore it's safe for multiple threads to use the method.

However if the method itself uses static variables then you should use appropriate MT protection. Also external methods you may be calling need to be safe...


Are the local variables "shared" across usages of the method?

No, they are not. Each thread executing the method has its own copy of the local variables, and they are independent of each other. When the method returns, the particular copy of locals for that particular thread is discarded. (*)

What happens for example if the static method is being called/used at the same time from different threads? Does one thread block until the other is complete etc?

No, they don’t; they will just execute the method on two separate stacks at the same time. If you actually want them to block, use the lock statement, which causes the second thread that enters the lock statement to wait until the first one returns from the lock statement. This may be necessary if your method accesses (non-local) fields, which are shared data.

In a threaded application, when should one not use a static method?

Whether you should use a static method or not depends on whether the method requires an object to operate on, but has nothing to do with whether your application is multi-threaded or not. For the purpose of threading, a static method is nothing special compared to a non-static method.

(*) This may no longer be true if you have a lambda expression or anonymous method inside the method that uses the local variables, but this is a technicality.


No method of any kind in C# shares local variables.

You may be thinking of Static functions in VB.