I am trying to run the following code using Mono on Ubuntu 18.10:
public class X
{
public X() { Console.WriteLine("Ctor X"); }
~X() { Console.WriteLine("Finalizer X"); }
private static Y _myY = new Y();
}
public class Y
{
public Y() { Console.WriteLine("Ctor Y"); }
~Y() { Console.WriteLine("Finalizer Y"); }
}
public class Program
{
static void Main()
{
X x = new X();
}
}
I get the following output most of the time (always in this order, although I thought that it might change from time to time since the finalizers order of execution is not deterministic).
Ctor X
Ctor Y
Finalizer X
Finalizer Y
But every once in a while the Y finalizer throws a System.NotSupportedException that seems to be originating from the FileStream.Write method that is writing to standard output.
Any ideas why this might happen? I thought maybe the stdout handle of Console is closed before the Y finalizer runs but this is only a theory.
It might be related to the fact that the order of collection is non-deterministic, meaning, sometimes the
Consolestatic class gets collected beforeY.Regarding the order of execution of the constructors and destroyers, I think it's always the same because:
The constructor of
Xis always called beforeY's because the defaultstaticconstructor is called only whenXis "touched" for the first time.The destroyer of
Xis always called beforeY's becauseYis a static member, meaning it's a long-lived instance (i.e. Gen2).Hope it helps!