Tuesday, May 02, 2006

How to stop an object from being garbage collected

You go to the MSDN site and you get this as a proper implementation of the IDisposable interface:

#region IDisposable Members
public void Dispose()

protected virtual void Dispose(bool isDisposing)
// Check to see if Dispose has already been called.
if (!_isDisposed)
_isDisposed=true; //this is what I added, I think it makes this thread safe
if (isDisposing)
//Clean up resources
_isDisposed = true;

In other words, implement IDisposable to clean up unmanaged resources. Well, unmanaged could be considered managed code from another thread. If your object starts a thread that calls an event, then when you exit the code block where you declared the object, then the event will never get fired. A pending action is unmanaged, therefore you can do something like:

while (!actionFinished) Thread.Sleep(1000);

the action should, of course, set actionFinished to true;