Horribleness aside, if I have a .NET webapp which has static variables scattered across multiple classes, what is neatest way to 'clear' them all back to null.
Off the top of my head, it would be to restart the application using
System.Web.HttpRuntime.UnloadAppDomain()
Reasons behind the question - We are caching a few very large Dictionary collections which are expensive to create, and on the odd occasion need to be reset.
Unloading sounds the simplest way, but you wouldn't want to do that very frequently; frankly I would be very dubious of any routine requirement to do this.
If you wanted to do it without unloading, you'd have to look on a case-by-case basis to understand the implications. In particular, forcibly setting something to null that was set to a value by the static constructor / type initializer / static field initializer could thoroughly break your application.
Note that static variables are rarely suitable for web apps, except perhaps for caches (and then must be carefully managed).
If you genuinely do have data like this, rather than multiple static variables you might look at instance variables on a state class that is help as a pseudo-singleton - then you only have one reference to swap per cluster of data.
Something that might be worth considering is having an event somewhere that the static code can subscribe to once only when initializing themselves, then trigger the event when needed, i.e.
myStaticData = new SomeExpensiveThreadSafeCacheDictionary();
GlobalKillSwitch.ResetCache += delegate { myStaticData.Clear(); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With