[Mono-list] Accessing member objects in destructors

Javier Martinez Alvarez jamaa@tid.es
Fri, 05 Mar 2004 15:39:22 +0100


Hi,
I think that the class can improved in two ways:
1 To make the class safe thread
2 To prevent  the call a finalize (destructor) when the Dispose is invocated
explicity, to a better performance and free memory early

public class T : IDispose {
        public void Dispose () {
lock(this) // 1
{
               	 Dispose (true);
GC.SupressFinalize(this)  // 2
}
        }
        ~T () {
                Dispose (false);
        }
        private bool disposed = false;
        private void Dispose (bool disposing) {
                if (!disposed) { // make sure we only dispose once
                        if (disposing) {
                                // managed disposes
                        }
                        // unmanaged disposes
                }
                disposed = true;
        }
}



> -----Original Message-----
> From: Jonathan Pryor [mailto:jonpryor@vt.edu]
>       class Test : IDisposable {
>               IDisposable nested;
>
>               public void Dispose ()
>               {
>                       Dispose (true);
>               }
>
>               ~Test ()
>               {
>                       Dispose (false);
>               }
>
>               protected virtual void Dispose (bool disposing)
>               {
>                       if (disposing) {
>                               // safe to access members
>                               if (nested != null)
>                                       nested.Dispose ();
>                       }
>                       // Always deal with unmanaged members here.
>               }
>       }

This code isn't recallable which it needs to be.  You need a local
variable which gets checked.

public class T : IDispose {
        public void Dispose () {
                Dispose (true);
        }
        ~T () {
                Dispose (false);
        }
        private bool disposed = false;
        private void Dispose (bool disposing) {
                if (!disposed) { // make sure we only dispose once
                        if (disposing) {
                                // managed disposes
                        }
                        // unmanaged disposes
                }
                disposed = true;
        }
}

I'm not sure if this applies to Mono but there is also some issues if an
object is resurrected (via WeakReference f.e., see
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/h
tml/frlrfsystemweakreferenceclasstopic.asp)

Chris
_______________________________________________
Mono-list maillist  -  Mono-list@lists.ximian.com
http://lists.ximian.com/mailman/listinfo/mono-list