I can't reproduce the problem on my laptop, but your DoSomething
method doesn't use any fields within the object. That means that the object can be finalized even while DoSomething
is running.
If you change your code to:
class Something
{
int x = 10;
public void DoSomething()
{
x++;
Console.WriteLine("Doing something");
Console.WriteLine("x = {0}", x);
}
~Something()
{
Console.WriteLine("Called finalizer");
}
}
... then I suspect you will always see DoingSomething
printed twice before "Called finalizer" - although the final "x = 12" may be printed after "Called finalizer".
Basically, finalization can be somewhat surprising - I very rarely find myself using it, and would encourage you to avoid finalizers wherever possible.