Singleton and GC

  • Thread starter Thread starter David
  • Start date Start date
D

David

Consider the following singleton:

public sealed class Foo {
private static readonly Foo instance = new Foo();
private Foo() {
//Do init work
}

public static Foo Instance {
get {
return instance;
}
}
}

Once the Instance property is accessed like so:

Foo fooInstance = Foo.Instance;

and assuming fooInstance is not used anywhere else in the application,

the instance of Foo is *never* garbage collected and will last for the
lifetime of the AppDomain (which could be an ASP.net AppDomain) because the
private static field - instance - will always hold a reference to the
instance of Foo.

Is this correct?

Thanks.
 
...

Foo fooInstance = Foo.Instance;

and assuming fooInstance is not used anywhere else in the application,

the instance of Foo is *never* garbage collected and will last for the
lifetime of the AppDomain (which could be an ASP.net AppDomain) because the
private static field - instance - will always hold a reference to the
instance of Foo.

Is this correct?

I think yes. A live reference to an object will make it ineligible for
GC. This means you can have a sort of memory leaks in C# - if you keep
references to objects you don't need.

Hope this helps(tm)
 
the instance of Foo is *never* garbage collected
and will last for the lifetime of the AppDomain
...Is this correct?

It will indeed not be garbage collected; re lasting
for the lifetime - it can't outlive it, but note that
it won't be created until the static class is first
accessed(there are some more complex rules, but
that is the rough version...)

Marc
 
David said:
Consider the following singleton:

public sealed class Foo {
private static readonly Foo instance = new Foo();
private Foo() {
//Do init work
}

public static Foo Instance {
get {
return instance;
}
}
}

Once the Instance property is accessed like so:

Foo fooInstance = Foo.Instance;

and assuming fooInstance is not used anywhere else in the application,

the instance of Foo is *never* garbage collected and will last for the
lifetime of the AppDomain (which could be an ASP.net AppDomain) because the
private static field - instance - will always hold a reference to the
instance of Foo.

Is this correct?

Not quite.

..NET does not use reference counting. .NET checks whether an object is
reachable.

The instance of Foo will always be reachable via Foo.Instance and will
therefore never be garbage collected.

(if the app domain where the class is loaded is unloaded then it becomes
unreachable and the instance can be garbage collected, but that is a
special case)

Arne
 
Back
Top