6

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
  }
Serguei Fedorov
  • 7,763
  • 9
  • 63
  • 94

2 Answers2

5

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 !

Jason De Oliveira
  • 1,732
  • 9
  • 16
  • Do you have an article or reference of some kind that touches more on this subject? I would be interesting in learning more about it. – David East Jun 21 '12 at 14:20
  • Look at the links that you can find in the comments of your question. You may also look here http://bytes.com/topic/c-sharp/answers/878381-static-variable-hell-asp-net and here http://www.foliotek.com/devblog/avoid-static-variables-in-asp-net/ StackOverFlow has also lots of posts. – Jason De Oliveira Jun 21 '12 at 16:03
  • 2
    Note that SOMETIMES you might need to use a static variables if you really need to share information amongst your whole application. But I would rather use a Singleton in this case. – Jason De Oliveira Jun 21 '12 at 16:08
  • Is there a way to tell ASP.NET to kill any static memory allocations associated with that session? – Serguei Fedorov Jun 21 '12 at 17:55
  • The only thing that you may do is to set the variable to null. But this will deallocate using the garbage collector for all sessions not just for one. You understand that all session use the same object in case of a static variable. – Jason De Oliveira Jun 21 '12 at 18:23
0

This is your standard CLR execution model, it is no different for asp.net. Static object are considered application's roots and are not garbage collected.

This is an old article on how garbage collection works in .net, but I think that all the principles are still the same: http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158