Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static objects in ASP.NET a waste of memory?

I was just wondering this the other day. I am not exactly sure how ASPX manages the garbage disposal, but as far as I can tell the "finished loading" does not remove static memory values or after the page has been reloaded. Static at least in terms of C means that the memory allocation follows your program until the program itself is shut down. Is this the same way in ASPX? If I have a static value and I go from Page A to Page B, is that static value still persistent in the RAM until they leave the application or is that value removed once I am no longer on Page A? (go to a different website removing their instance off the application pool in the server).

From what I have experienced:

  public static class foo
  {
      public static int x;
  }

  protected void Page_Load(object sender, EventArgs e)
  {
      foo.x++; //This will continue to increment from the last value before reload
  }
like image 209
Serguei Fedorov Avatar asked Jun 20 '12 21:06

Serguei Fedorov


1 Answers

Static classes should be avoided in ASP.NET. They stay in memory until the application is restarted and are subject to many concurrency errors and race conditions.

And closing a user session (browser session) does not restart the application ! They stay in memory even if a user leaves and comes back. So really really avoid static classes !

like image 148
Jason De Oliveira Avatar answered Sep 28 '22 08:09

Jason De Oliveira