tags:

views:

124

answers:

2

I have some static classes in my application. When I run the application, stop debugging and restart I notice that these variables stay in memory! So when the application terminates they are left behind and are reattached to the next instance of the application. This produces really crazy results as you'd expect.

Can you programatically tell a static variable to destroy itself when the application terminates?

+6  A: 

Static variables remain as long as the AppDomain that contains them remains active. If you're seeing them persist between debugging sessions, that means the app does not stop running when you stop debugging - it's the same instance both times. Try restarting the web server.

I would add that if the fact that static variables tend to be persistent is causing crazy results, you're probably not using them right, and possibly shouldn't be using static variables at all.

Joel Mueller
Doesn't that make static variables totally useless in ASP.NET? I mean who is going to write code to start/stop web servers just because they used the word "static" in their code?
Petras
That depends what you're using them for. They can be useful, but they make testing difficult, and if they're not read-only variables, you need to manually manage locking and such to avoid melt-downs under load. You might be better off storing your values in application state: `Application["foo"] = value;`
Joel Mueller
The Application object is just another static variable. It happens to also have some methods to manage locking, but it doesn't fundamentally behave any differently than other static variables.
RickNZ
Yes, and? You would suggest manual lock management to the OP? I mentioned application state specifically because it manages locking for you, and the OP seems to want shared state.
Joel Mueller
+1  A: 

Stopping the debugger doesn't stop IIS or Cassini.

If you're using Cassini, you need to explicitly stop it from the command tray in order to get it to recycle.

Otherwise, you can try modifying web.config to force a recycle.

I filed a bug about this once on Connect; Microsoft said it was "by design."

RickNZ