[Mono-list] Dispose method is never called
Gonzalo Paniagua Javier
gonzalo@ximian.com
06 Jul 2003 20:29:01 +0200
El dom, 06-07-2003 a las 17:20, Giuseppe Greco escribió:
> 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.
Is it called under windows? I think it's not because MyThreadMethod is
accessing isDisposed field, which belongs to the class instance. That's
why it's never disposed.
-Gonzalo