Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static methods ever safe in web development?

Tags:

c#

asp.net

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?

like image 337
Mr Smith Avatar asked Jan 09 '14 20:01

Mr Smith


3 Answers

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.

like image 127
Brian Ball Avatar answered Oct 24 '22 15:10

Brian Ball


Yes they can be safe.

"Pure functions" that don't have side effects are an example.

like image 20
Jean-Bernard Pellerin Avatar answered Oct 24 '22 15:10

Jean-Bernard Pellerin


I use:

  • Static startup and shutdown methods called from the Application_Start and Application_End methods in Global.asax.cs:
    • These methods are safer (single-threaded) than static constructors, for constructing static data
    • But beware of other static methods of Global, for example Session_Start and Application_Error, which may not be serialized.
  • Static classes to define extension methods
  • Static methods which have no side effects (which process their input parameters and return a result, without modifying global/static data)
  • Static functions which are explicitly thread-safe e.g. because they use lock in their implementation
like image 4
ChrisW Avatar answered Oct 24 '22 15:10

ChrisW