Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can there be concurrency issues when using C# class with only static methods and no variables?

Have I understood correctly that all threads have copy of method's variables in their own stack so there won't be problems when a static method is called from different threads?

like image 457
char m Avatar asked Jan 04 '12 18:01

char m


1 Answers

Yes and no. If the parameters are value types, then yes they have their own copies. Or if the reference type is immutable, then it can't be altered and you have no issues. However, if the parameters are mutable reference types, then there are still possible thread safety issues to consider with the arguments being passed in.

Does that make sense? If you pass a reference type as an argument, it's reference is passed "by value" so it's a new reference that refers back to the old object. Thus you could have two different threads potentially altering the same object in a non-thread-safe way.

If each of those instances are created and used only in the thread using them, then chances are low that you'd get bit, but I just wanted to emphasize that just because you're using static methods with only locals/parameters is not a guarantee of thread-safety (same with instance of course as noted by Chris).

like image 85
James Michael Hare Avatar answered Sep 22 '22 18:09

James Michael Hare