Skip to content

Conversation

AustinWise
Copy link
Contributor

@AustinWise AustinWise commented Jun 22, 2024

This matches the existing feature in CoreCLR:

https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/finalizerthread.cpp#L250

I tested with the following program. I observed that the finalizer was not triggered until I created a low memory condition on my computer.

using System;
using System.Runtime.CompilerServices;
using System.Threading;


internal class Program
{
    static void Main(string[] args)
    {
        // The managed finalize loop (which checks for low memory) is not started until the first finalization request.
        // This program does not allocate enough for the GC to request finalization, so we manually trigger it.
        GC.WaitForPendingFinalizers();
        Alloc();
        Thread.Sleep(-1);
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void Alloc() => new MyFinalizableObject();
}

class MyFinalizableObject
{
    ~MyFinalizableObject()
    {
        Console.WriteLine("~MyFinalizableObject");
    }
}

Some notes:

  • PalCompatibleWaitAny only supports multiple objects on Windows. The low memory event is only available on Windows, so this works out.
  • It looks like CoreCLR only collects generation 0 on low memory. I have updated NativeAot to do the same, but I'm not sure that is ideal. Would collecting all generations make more sense?

@dotnet-policy-service dotnet-policy-service bot added the community-contribution Indicates that the PR has been added by a community member label Jun 22, 2024
Copy link
Contributor

Tagging subscribers to this area: @agocke, @MichalStrehovsky, @jkotas
See info in area-owners.md if you want to be subscribed.

Copy link
Member

@jkotas jkotas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great. Thank you!

@jkotas jkotas merged commit c07a81f into dotnet:main Jul 2, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Aug 1, 2024
@AustinWise AustinWise deleted the austin/LowMemory branch August 17, 2024 20:19
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-NativeAOT-coreclr community-contribution Indicates that the PR has been added by a community member
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants