Alex Rivera | Logout

What happens when you call a static method in C#?

Asked 2011-12-22T15:55:18.607
9

When you create an instance of a class, all the variables in that instance is specific to that instance and get killed when the instance is out of scope. But how does it work in a static method? Suppose two people call System.Math.Abs() at exactly the same time. How does the runtime differentiate between the two callers? Is this where threading comes in? Are separate threads automatically created for each caller?

Edit
Report

1 Answer

6

All static members of a class exist even if no instances of the class exist. They get initialized sometime before first use and get cleaned up when the program is complete.

If you had two simultaneous calls to a static method, they would be working with the same copy of any static members of the class (if they use them). So if the static method operates on a static member (or parameter), it should do so in a thread safe way. If the static method only operates on locals then the method itself is typically thread safe.

As for how does the runtime differentiate between two callers, this is the essence of threading. Each thread has its own call stack with its own copy of any local variables, parameters, return address, etc. So the two calls do not get confused and each return to their caller correctly. The only concern, again, is if the static method operates on a static member that isn't thread safe (or a parameter that isn't thread safe).

answered 2011-12-22T16:02:31.403

Your Answer