Are static methods safe in web development?

I used static "helper" methods and saw how other people use them. But are they safe in a multi-threaded environment such as a website? Are static methods always susceptible to multi-threaded threads coming in at the same time and causing problems?

When do you use them?

+7
source share
3 answers

Yes, they can be very safe. There are many examples in ASP.NET where there are static methods. System.Web.HttpUtility is an entire class that contains only static methods (except for methods that it inherits from System.Object ).

The largest red flag to search for is static code that modifies a shared resource (for example, a static property and / or field). You can perform such updates and safely code them, but whenever you see code that modifies a shared resource, this should make you pause and make sure everything is done correctly.

+7
source share

Yes, they can be safe.

Pure functions that have no side effects are an example.

+4
source share

I use:

  • Static startup and shutdown methods called by the Application_Start and Application_End methods in Global.asax.cs :
    • These methods are safer (single-threaded) than static constructors for building static data.
    • But beware of other static Global methods like Session_Start and Application_Error that cannot be serialized.
  • Static classes for defining extension methods
  • Static methods that have no side effects (which process their input parameters and return the result without changing global / static data)
  • Static functions that are explicitly thread safe, for example. because they use lock in their implementation
+4
source share

All Articles