Skip to content

Finalizer no longer called in .NET Core 2.0 after GC.Collect / GC.WaitForPendingFinalizers #1115

Closed

Description

@sfmskywalker

Update: I also reported this issue here, since that repo might be more appropriate. I'll close either this one or the other once I know for sure.

Finalizer no longer called in .NET Core 2.0 after GC.Collect / GC.WaitForPendingFinalizers

As of .NET Core 2.0, an object's finalizer is no longer called when calling GC.Collect and GC.WaitForPendingFinalizers.

General

To be clear: the following code works as advertised in .NET Framework 4.7 and earlier; .NET Core 1.1 and earlier; but not in .NET Core 2.0:

[TestClass]
public class GarbageCollectionTest
{
    [TestMethod]
    [Description("Asserts that an un-rooted object's finalizer will be called.")]
    public void GarbageCollectionTest01()
    {
        // Instantiate a spy to record that the Foo finalizer is called.
        var spy = new Spy();

        // Instantiate a new Foo.
        var foo = new Foo(spy);

        // Unroot foo.
        foo = null;

        // Force a collection.
        GC.Collect(0, GCCollectionMode.Forced, blocking: true);

        // Wait for all finalizers to have executed.
        GC.WaitForPendingFinalizers();

        // Assert that Foo's finalizer is called.
        // WARNING: This assertion fails in .NET Core 2.0, but works in .NET Core 1.1 and .NET Framework 4.7 and before.
        Assert.IsTrue(spy.FinalizerIsCalled);
    }

    private class Spy
    {
        public bool FinalizerIsCalled { get; set; }
    }

    private class Foo
    {
        ~Foo()
        {
            spy.FinalizerIsCalled = true;
        }

        public Foo(Spy spy)
        {
            this.spy = spy;
        }

        private readonly Spy spy;
    }
}

Unit test output:

image

To demonstrate the issue, I created a unit test project for the following frameworks which all share the same .cs file:

  • .NET Framework 4.7 [passing]
  • .NET Core 1.0 [passing]
  • .NET Core 1.1 [passing]
  • .NET Core 2.0 [failing]

GarbageCollectionTests.zip

Activity

  1. jkotas commented on Nov 24, 2017

    @jkotas
    Member

    CoreCLR repo is the right place for this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions