Skip to content

WPF control is not reclaimed on NET9 by GC #9467

Description

@minaew

Description

GC does not reclaim control memory in following scenario. The control is placed in the visual tree and then removed from it. Conditions must be met:

  • PresentationTraceSources.Refresh() call
  • there is a subscriber to the Unloaded event of control

Reproduction Steps

Run test TestLeak in project targeting net9.0-windows. NUnit version is 3.12.0.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using NUnit.Framework;

namespace Sample {
    [TestFixture]
    public class MemoryTests {
        [Test]
        public void TestLeak() {
            PresentationTraceSources.Refresh();
            var window = new Window();
            var wr = AddAndRemoveImage(window);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.IsFalse(wr.IsAlive);
        }

        static WeakReference AddAndRemoveImage(Window window) {
            var img = new Image();
            var wr = new WeakReference(img);
            var holder = new ImageHolder(img);
            window.Content = img;
            window.Show();
            DoEvents();
            window.Content = null;
            DoEvents();
            return wr;
        }

        static void DoEvents() {
            var frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.InvokeAsync(() => frame.Continue = false, DispatcherPriority.Background);
            Dispatcher.PushFrame(frame);
        }

        class ImageHolder {
            readonly Image image;
            public ImageHolder(Image image) {
                this.image = image;
                this.image.Loaded += OnLoaded;
                this.image.Unloaded += OnUnloaded;
            }

            void OnLoaded(object sender, RoutedEventArgs e) {
                Debug.WriteLine("OnLoaded");
            }

            void OnUnloaded(object sender, RoutedEventArgs e) {
                Debug.WriteLine("OnUnloaded");
            }
        }
    }
}

Expected behavior

The test passes.

Actual behavior

The test fails.

Regression?

This works in net8.0 and net462.

Known Workarounds

No response

Configuration

.NET: 9.0.0-preview.6.24327.6
OS: Windows 10, Version 22H2 (OS Build 19045.4651)
Architecture: x64

Other information

No response

Activity

  1. teo-tsirpanis commented on Jul 12, 2024

    @teo-tsirpanis

    Can you add [MethodImpl(MethodImplOptions.NoInlining)] in AddAndRemoveImage and try again? There's a chance the JIT has inlined AddAndRemoveImage, which might have extended the lifetime of img.

  2. EgorBo commented on Jul 12, 2024

    @EgorBo
    Member

    Can you add [MethodImpl(MethodImplOptions.NoInlining)] in AddAndRemoveImage and try again? There's a chance the JIT has inlined AddAndRemoveImage, which might have extended the lifetime of img.

    if it's inlined, then it means it's Tier1/Fullopts, hence, precise liveness is expected, so should also be claimed. I quickly tried the repro locally and it seems like there is indeed a change in behaviour between net8.0-windows and net9.0-windows for both Tier0 and Tier1, so shouldn't be JIT's fault.

  3. minaew commented on Jul 12, 2024

    @minaew
    Author

    Can you add [MethodImpl(MethodImplOptions.NoInlining)] in AddAndRemoveImage and try again? There's a chance the JIT has inlined AddAndRemoveImage, which might have extended the lifetime of img.

    Thanks. I tried, still no success.

  4. EgorBo commented on Jul 12, 2024

    @EgorBo
    Member

    Might be the same issue as dotnet/runtime#104218 cc @VSadov

  5. minaew commented on Jul 12, 2024

    @minaew
    Author

    The RetryAttribute helps. Less tries is required if test closes the window.

  6. teo-tsirpanis commented on Jul 12, 2024

    @teo-tsirpanis

    I would also suggest running GC and waiting for pending finalizers in your tests more than once. The object might not be released on the first try.

  7. minaew commented on Jul 16, 2024

    @minaew
    Author

    I would also suggest running GC and waiting for pending finalizers in your tests more than once. The object might not be released on the first try.

    This also does not help, event increases the number of required retries.

  8. minaew commented on Jul 16, 2024

    @minaew
    Author

    By the way, if I hide window (window.Hide()) the test becomes much more stable, but still not 100%.

  9. mangod9 commented on Jul 18, 2024

    @mangod9
    Member

    Can you add [MethodImpl(MethodImplOptions.NoInlining)] in AddAndRemoveImage and try again? There's a chance the JIT has inlined AddAndRemoveImage, which might have extended the lifetime of img.

    if it's inlined, then it means it's Tier1/Fullopts, hence, precise liveness is expected, so should also be claimed. I quickly tried the repro locally and it seems like there is indeed a change in behaviour between net8.0-windows and net9.0-windows for both Tier0 and Tier1, so shouldn't be JIT's fault.

    @EgorBo, can you please clarify what you mean by behavior change here?

  10. added this to the 9.0.0 milestone on Jul 18, 2024
  11. EgorBo commented on Jul 18, 2024

    @EgorBo
    Member

    Can you add [MethodImpl(MethodImplOptions.NoInlining)] in AddAndRemoveImage and try again? There's a chance the JIT has inlined AddAndRemoveImage, which might have extended the lifetime of img.

    if it's inlined, then it means it's Tier1/Fullopts, hence, precise liveness is expected, so should also be claimed. I quickly tried the repro locally and it seems like there is indeed a change in behaviour between net8.0-windows and net9.0-windows for both Tier0 and Tier1, so shouldn't be JIT's fault.

    @EgorBo, can you please clarify what you mean by behavior change here?

                GC.Collect();
                GC.WaitForPendingFinalizers();

    do not longer call the finalizer right away in .NET 9.0 while it's consistently calling it in .NET 8.0. Bot for optimized codegen and unoptimized. I know it's not supposed to be 100% guaranteed, but it's just what the author is complaining

  12. mangod9 commented on Jul 19, 2024

    @mangod9
    Member

    Ok thanks. Adding @jkotas @VSadov as well, possibly related to moving finalizer loop to managed?

  13. jkotas commented on Jul 21, 2024

    @jkotas
    Member

    possibly related to moving finalizer loop to managed?

    It is very unlikely to be related to that change.

    I am not able to reproduce the issue. Could you please create a scratch project on github that can be cloned and run to reproduce
    it?

  14. 16 remaining items

  15. mangod9 commented on Jul 25, 2024

    @mangod9
    Member

    can this issue be moved to wpf repo ?

  16. transferred this issue fromdotnet/runtimeon Jul 25, 2024
  17. alexdi220 commented on Mar 12, 2025

    @alexdi220

    Hello there. Any updates on this?

  18. lindexi commented on Mar 12, 2025

    @lindexi
    Member

    Hello there. Any updates on this?

    Cc @rchauhan18 and @dipeshmsft , could you review my PR(#9463 )?

  19. dipeshmsft commented on Mar 12, 2025

    @dipeshmsft
    Member

    Sure @lindexi, I will take a look at the PR in the coming week.

  20. added theissue type on Mar 29, 2025
  21. added
    Bug
    regression
    on Mar 29, 2025
  22. removed this from the 9.0.0 milestone on Apr 4, 2025
  23. locked and limited conversation to collaborators on May 5, 2025
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

    🚧 work in progressBugregression

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions