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()
{
Dispose(true);
GC.SuppressFinalize(this);
}
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;
}
#endregion
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;
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
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;
}
#endregion
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;
Comments
Be the first to post a comment