Does the DoSomething() method cause memory leakage?
public static class AppContext
{
public static int ApplicationStateId {get; set}
...
}
public class MyService
{
public void DoSomething()
{
....
if(AppContext.ApplicationStateId == 1)
{
//do something
}
}
}
var service = new MyService();
service.DoSomething();
This means that static variables and everything they reference will never be garbage collected.
Michael said in 8 Ways You can Cause Memory Leaks in .NET.
There is no "leak" here; this is simply the expected behavior. Yes, anything that is reachable via a static field will will not be collected by GC, but this is usually correct in terms of some kind of global state. By "leak", we're usually referring to unexpected or inexplicable memory retention. The most common scenario there is with static events which sound like a great idea, but make it very easy to keep entire segments of long-redundant objects alive. For example:
SomeType.SomeStaticEvent += obj.HandleTheThing;
which now means that the object from obj is now retained forever (or at least until the delegate is explicitly removed from the event), and anything that obj can see: is now retained forever, etc.
In the case shown in the question, there aren't even any objects - just an integer. I don't think you need to worry about the cost of retaining an integer over the duration of an app-domain, especially if your app-domain requires that integer to be known for the duration.
I'd be more concerned about things like concurrency - whether that means "multiple current user stations", or low level details like volatility and register usage of fields.
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