C# Question - I'm trying to determine whether it is OK to use a static method where, within the method it does have some local variables it uses. Are the local variables "shared" across usages of the method? 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?
Perhaps the generalised question is, in a threaded application, when should one "not" being using a static method?
In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.
Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.
A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared, e.g. to be used as a count variable.
Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With