Getting a NotSupportedException when writing from finalizer

68 Views Asked by At

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.

1

There are 1 best solutions below

2
Itay Podhajcer On

It might be related to the fact that the order of collection is non-deterministic, meaning, sometimes the Console static class gets collected before Y.

Regarding the order of execution of the constructors and destroyers, I think it's always the same because:

  • The constructor of X is always called before Y's because the default static constructor is called only when X is "touched" for the first time.

  • The destroyer of X is always called before Y's because Y is a static member, meaning it's a long-lived instance (i.e. Gen2).

Hope it helps!