Destructors are weird. I was attempting to eliminate the need of using the disposable pattern by using 'smart' reference management, ensuring that the garbage collector could collect objects at the correct time. In one of my destructors I had to wait for an event from another object, which I noticed it didn't. The application simply shut down and the destructor was terminated in middle of execution. I'd expect a destructor is always allowed to finish running, but as the following test indicates that is not true.
using System;
using System.Diagnostics;
using System.Threading;
namespace DestructorTest
{
class Program
{
static void Main( string[] args )
{
new DestructorTest();
new LoopDestructorTest();
using ( new DisposableTest() ) { }
}
}
class DestructorTest
{
~DestructorTest()
{
// This isn't allowed to finish.
Thread.Sleep( 10000 );
}
}
class LoopDestructorTest
{
~LoopDestructorTest()
{
int cur = 0;
for ( int i = 0; i < int.MaxValue; ++i )
{
cur = i;
}
// This isn't allowed to finish.
Debug.WriteLine( cur );
}
}
class DisposableTest : IDisposable
{
public void Dispose()
{
// This of course, is allowed to finish.
Thread.Sleep( 10000 );
}
}
}
So, aren't destructors guaranteed to finish running?
IDisposable
pattern to have reliable destruction and resource release. – Daniel HilgarthDispose()
isn't madness? What's the difference? – Steven JeurisThe Finalize method might not run to completion or might not run at all in the following exceptional circumstances:
– Tung