Disposing Pattern

S

sunitabalakrishna

Hi,

Could someone explain me if I need to implement the Dispose pattern on
managed objects that hold objects which have longer life or is a
singleton?

Example -
Class A holds Class Global where Class Global is a singleton.

So should Class A have


private Global g;
#region IDisposable Members

public void Dispose() {
// TODO: Add TagDataIOExecutor.Dispose implementation
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing) {
g = null;
}

~A() {
Dispose(false);
}

#endregion


-Thanks
mb
 
T

Truong Hong Thi

Hi mb,

Even if Global implements singleton pattern, setting "g = null" does
not mean you dispose it. It just means g will mo longer reference that
singleton's memory location. Did you omit a line like: g.Dispose() ? If
no, your class does not hold resources that need disposing, you don't
need to consider the dispose pattern at all.
Could someone explain me if I need to implement the Dispose pattern on
managed objects that hold objects which have longer life or is a
singleton?
Generally, a class should not dispose object if it does not control the
object's life time.

Regards,
Thi
 
S

sunitabalakrishna

Thank you for the reply.

Its true 'a' an instance of A does not control the life span of 'g'.
But how would GC determine that 'a' is no longer in use?
 
J

Jon Skeet [C# MVP]

Thank you for the reply.

Its true 'a' an instance of A does not control the life span of 'g'.
But how would GC determine that 'a' is no longer in use?

The GC walks the forest of "reachable" objects, taking its "roots" from
static variables and local variables in all the stack frames in all
threads. It starts out with the assumption that everything can be
thrown away, and marks those objects which it finds can't be thrown
away.

It's more complex than that, partly due to generations, but that's the
basic thrust of it.
See http://msdn.microsoft.com/msdnmag/issues/1100/GCI/default.aspx for
more details.

Jon
 
S

sunitabalakrishna

Thanks you for the explanation. I tried a sample example and did
observe the same behaviour.
 

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