[Mono-list] Dispose method is never called

James F. Bellinger zer@neo.rr.com
Sun, 6 Jul 2003 12:20:54 -0400


It's possible the thread is being garbage-collected before the class itself.
There's no guarantee that any object will be swept before or after any
other, and if MyClass is dead, myThread is certainly also. Are you sure the
destructor is not being called? It's possible that it is getting up to
myThread.Join() and having an exception because myThread has already been
collected. If there is an exception in a destructor the destructor will be
silently exited.

----- Original Message ----- 
From: "Giuseppe Greco" <giuseppe.greco@agamura.com>
To: "Mono" <mono-list@ximian.com>
Sent: Sunday, July 06, 2003 11:20 AM
Subject: [Mono-list] Dispose method is never called


> Hi all,
>
> I've a class that starts a worker thread like
> this:
>
> class MyClass
> {
>   bool isDisposed = false;
>   Thread myThread;
>
>   public MyClass()
>   {
>       ...
>       myThread = new Thread(new ThreadStart(MyThreadMethod));
>       myThread.Start();
>       myThread.IsBackground = true;
>    }
>
>   ~MyClass()
>   {
>     Dispose(false)
>   }
>
>   public void Dispose()
>   {
>     Dispose(true);
>     GC.SuppressFinalize(this);
>   }
>
>   protected virtual void Dispose(bool disposing)
>   {
>     if (!isDisposed) {
>       isDisposed = true;
>
>       myThread.Join(); // should wait until MyThreadMethod()
>                        // completes its work...
>       myThread = null;
>
>       if (disposing) {
>         ...
>       }
>     }
>   }
>
>   private void MyThreadMethod()
>   {
>     while (!isDisposed) {
>       ...
>     {
>   }
> }
>
> Well, in the class above, the Dispose() method is never
> called. This is a problem if one needs to wait until the
> thread has finished its work -- Thread.Join() should block
> until then.
>
> The destructor -- ~MyClass() -- is never called.
>
> Gius_.