[Mono-list] Accessing member objects in destructors

Chris Day chrisd@monkey.biz
Fri, 5 Mar 2004 09:40:06 +1100


> -----Original Message-----
> From: Jonathan Pryor [mailto:jonpryor@vt.edu]=20
> 	class Test : IDisposable {
> 		IDisposable nested;
>=20
> 		public void Dispose ()
> 		{
> 			Dispose (true);
> 		}
>=20
> 		~Test ()
> 		{
> 			Dispose (false);
> 		}
>=20
> 		protected virtual void Dispose (bool disposing)
> 		{
> 			if (disposing) {
> 				// safe to access members
> 				if (nested !=3D 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 =3D false;
	private void Dispose (bool disposing) {
		if (!disposed) { // make sure we only dispose once
			if (disposing) {
				// managed disposes
			}
			// unmanaged disposes
		}
		disposed =3D 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=3D/library/en-us/cpref/=
h
tml/frlrfsystemweakreferenceclasstopic.asp)

Chris