Singleton and GC

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.
 
M

Michael Justin

...

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)
 
M

Marc Gravell

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
 
A

Arne Vajhøj

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top