Good morning! Suppose we have the following class:
class MultithreadOperation : IDisposable
{
private IList<Thread> operationThreads;
public void StartOperation()
{
}
public void StopOperation()
{
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
disposed = true;
if (disposing)
{
#1:
StopOperation();
}
#2:
StopOperation();
}
}
~MultithreadOperation()
{
Dispose(false);
}
}
Actually, I need to stop all threads if the instance is deleted. In addition, I need to stop all threads if the instance is garbage collected (otherwise the threads will still be alive, which is bad for me). It is definitely, completely legal to refer to the StopOperation () method in place # 1.
I want to know if there are any pitfalls if we call StopOperation () in place # 2? As far as I understand, the list of threads may already be garbage collected when ~ MultithreadOperation () is executed. In addition, I saw many recommendations to avoid code that references managed resources in the Finalize implementation, especially instance fields.
.
!