I've used static "helper" methods & seen other people use them. But are they ever safe in a multi-threaded environment like a web site? Aren't static methods always susceptible to multple threads entering at the same time and causing problems?
When do you use them?
Yes, they can be very safe. There are plenty of examples in ASP.NET itself where there are static methods. System.Web.HttpUtility is an entire class that contains nothing but static methods (except the methods that it inherits from System.Object
).
The biggest red flag to look for is static code that modifies a shared resource (such as a static property and/or field). You can perform such updates and code them safely, but whenever you see code that modifies a shared resource, it should cause you to pause and verify that it was done correctly.
Yes they can be safe.
"Pure functions" that don't have side effects are an example.
I use:
Application_Start
and Application_End
methods in Global.asax.cs:
Session_Start
and Application_Error
, which may not be serialized.lock
in their implementationIf 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