diff --git a/src/Controls/src/Core/Internals/WeakEventProxy.cs b/src/Controls/src/Core/Internals/WeakEventProxy.cs index 6f0f1b0af82d..04da96a015bb 100644 --- a/src/Controls/src/Core/Internals/WeakEventProxy.cs +++ b/src/Controls/src/Core/Internals/WeakEventProxy.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Specialized; using System.ComponentModel; +using Microsoft.Maui.Controls.Shapes; // NOTE: warning disabled for netstandard projects #pragma warning disable 0436 @@ -152,4 +153,62 @@ public override void Unsubscribe() base.Unsubscribe(); } } + + /// + /// A "proxy" class for subscribing Geometry and PathGeometry invalidation via WeakReference. + /// General usage is to store this in a member variable and call Subscribe()/Unsubscribe() appropriately. + /// Your class should have a finalizer that calls Unsubscribe() to prevent WeakGeometryChangedProxy objects from leaking. + /// + class WeakGeometryChangedProxy : WeakEventProxy + { + public WeakGeometryChangedProxy() { } + + public WeakGeometryChangedProxy(Geometry source, EventHandler handler) + { + Subscribe(source, handler); + } + + void OnGeometryChanged(object? sender, EventArgs e) + { + if (TryGetHandler(out var handler)) + { + handler(sender, e); + } + else + { + Unsubscribe(); + } + } + + public override void Subscribe(Geometry source, EventHandler handler) + { + if (TryGetSource(out var s)) + { + s.PropertyChanged -= OnGeometryChanged; + + if (s is PathGeometry oldPathGeometry) + oldPathGeometry.InvalidatePathGeometryRequested -= OnGeometryChanged; + } + + source.PropertyChanged += OnGeometryChanged; + + if (source is PathGeometry pathGeometry) + pathGeometry.InvalidatePathGeometryRequested += OnGeometryChanged; + + base.Subscribe(source, handler); + } + + public override void Unsubscribe() + { + if (TryGetSource(out var s)) + { + s.PropertyChanged -= OnGeometryChanged; + + if (s is PathGeometry pathGeometry) + pathGeometry.InvalidatePathGeometryRequested -= OnGeometryChanged; + } + + base.Unsubscribe(); + } + } } diff --git a/src/Controls/src/Core/Shapes/Path.cs b/src/Controls/src/Core/Shapes/Path.cs index 264c48d2875e..44b6f4763775 100644 --- a/src/Controls/src/Core/Shapes/Path.cs +++ b/src/Controls/src/Core/Shapes/Path.cs @@ -11,6 +11,11 @@ namespace Microsoft.Maui.Controls.Shapes /// public sealed partial class Path : Shape, IShape { + WeakGeometryChangedProxy _dataProxy; + EventHandler _dataChanged; + WeakNotifyPropertyChangedProxy _transformProxy; + PropertyChangedEventHandler _transformChanged; + /// /// Initializes a new instance of the class. /// @@ -18,6 +23,12 @@ public Path() : base() { } + ~Path() + { + _dataProxy?.Unsubscribe(); + _transformProxy?.Unsubscribe(); + } + public Path(Geometry data) : this() { Data = data; @@ -26,12 +37,30 @@ public Path(Geometry data) : this() /// Bindable property for . public static readonly BindableProperty DataProperty = BindableProperty.Create(nameof(Data), typeof(Geometry), typeof(Path), null, - propertyChanged: OnGeometryPropertyChanged); + propertyChanging: (bindable, oldValue, newValue) => + { + if (oldValue != null) + (bindable as Path)?.StopNotifyingDataChanges(); + }, + propertyChanged: (bindable, oldValue, newValue) => + { + if (newValue != null) + (bindable as Path)?.NotifyDataChanges(); + }); /// Bindable property for . public static readonly BindableProperty RenderTransformProperty = BindableProperty.Create(nameof(RenderTransform), typeof(Transform), typeof(Path), null, - propertyChanged: OnTransformPropertyChanged); + propertyChanging: (bindable, oldValue, newValue) => + { + if (oldValue != null) + (bindable as Path)?.StopNotifyingTransformChanges(); + }, + propertyChanged: (bindable, oldValue, newValue) => + { + if (newValue != null) + (bindable as Path)?.NotifyTransformChanges(); + }); /// /// Gets or sets the that specifies the shape to be drawn. This is a bindable property. @@ -52,46 +81,38 @@ public Transform RenderTransform get { return (Transform)GetValue(RenderTransformProperty); } } - static void OnGeometryPropertyChanged(BindableObject bindable, object oldValue, object newValue) + void NotifyDataChanges() { - if (oldValue != null) - { - (oldValue as Geometry).PropertyChanged -= (bindable as Path).OnGeometryPropertyChanged; - - if (oldValue is PathGeometry pathGeometry) - pathGeometry.InvalidatePathGeometryRequested -= (bindable as Path).OnInvalidatePathGeometryRequested; - } + var data = Data; - if (newValue != null) + if (data != null) { - (newValue as Geometry).PropertyChanged += (bindable as Path).OnGeometryPropertyChanged; - - if (newValue is PathGeometry pathGeometry) - pathGeometry.InvalidatePathGeometryRequested += (bindable as Path).OnInvalidatePathGeometryRequested; + _dataChanged ??= (sender, e) => OnPropertyChanged(nameof(Data)); + _dataProxy ??= new WeakGeometryChangedProxy(); + _dataProxy.Subscribe(data, _dataChanged); } } - static void OnTransformPropertyChanged(BindableObject bindable, object oldValue, object newValue) + void StopNotifyingDataChanges() { - if (oldValue != null) - { - (oldValue as Transform).PropertyChanged -= (bindable as Path).OnTransformPropertyChanged; - } - - if (newValue != null) - { - (newValue as Transform).PropertyChanged += (bindable as Path).OnTransformPropertyChanged; - } + _dataProxy?.Unsubscribe(); } - void OnGeometryPropertyChanged(object sender, PropertyChangedEventArgs args) + void NotifyTransformChanges() { - OnPropertyChanged(nameof(Data)); + var renderTransform = RenderTransform; + + if (renderTransform != null) + { + _transformChanged ??= OnTransformPropertyChanged; + _transformProxy ??= new WeakNotifyPropertyChangedProxy(); + _transformProxy.Subscribe(renderTransform, _transformChanged); + } } - void OnInvalidatePathGeometryRequested(object sender, EventArgs e) + void StopNotifyingTransformChanges() { - OnPropertyChanged(nameof(Data)); + _transformProxy?.Unsubscribe(); } void OnTransformPropertyChanged(object sender, PropertyChangedEventArgs args) diff --git a/src/Controls/tests/Core.UnitTests/Shapes/PathSharedResourcesMemoryLeakTests.cs b/src/Controls/tests/Core.UnitTests/Shapes/PathSharedResourcesMemoryLeakTests.cs new file mode 100644 index 000000000000..7ef29c2166b4 --- /dev/null +++ b/src/Controls/tests/Core.UnitTests/Shapes/PathSharedResourcesMemoryLeakTests.cs @@ -0,0 +1,115 @@ +using System; +using Microsoft.Maui.Controls.Shapes; +using Microsoft.Maui.Graphics; +using Xunit; + +namespace Microsoft.Maui.Controls.Core.UnitTests.Shapes; + +public class PathSharedResourcesMemoryLeakTests : BaseTestFixture +{ + // NOTE: Path creation MUST be in a separate method. + // If created inline in the test method, the JIT keeps local variables alive for the + // entire method scope in debug mode — making the path uncollectable regardless of the fix. + // This is the standard .NET pattern for writing reliable GC/leak unit tests. + + static WeakReference CreatePathWithGeometry(PathGeometry geometry) + { + var path = new Path { Data = geometry }; + return new WeakReference(path); + } + + static WeakReference CreatePathWithTransform(ScaleTransform transform) + { + var path = new Path { RenderTransform = transform }; + return new WeakReference(path); + } + + static WeakReference CreatePathWithBoth(PathGeometry geometry, ScaleTransform transform) + { + var path = new Path { Data = geometry, RenderTransform = transform }; + return new WeakReference(path); + } + + [Fact] + public void SharedPathGeometry_DoesNotKeepPathAlive() + { + var sharedGeometry = new PathGeometry + { + Figures = new PathFigureCollection + { + new PathFigure + { + StartPoint = new Point(0, 0), + Segments = new PathSegmentCollection + { + new LineSegment { Point = new Point(100, 100) } + } + } + } + }; + + var pathRef = CreatePathWithGeometry(sharedGeometry); + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + Assert.False(pathRef.IsAlive, + "Path was not collected. The shared PathGeometry is holding a strong reference to " + + "Path via its PropertyChanged event handler. Use WeakGeometryChangedProxy to fix."); + + // Ensures sharedGeometry is a live GC root during the Collect calls above. + GC.KeepAlive(sharedGeometry); + } + + [Fact] + public void SharedRenderTransform_DoesNotKeepPathAlive() + { + var sharedTransform = new ScaleTransform(1.5, 1.5) { CenterX = 50, CenterY = 50 }; + + var pathRef = CreatePathWithTransform(sharedTransform); + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + Assert.False(pathRef.IsAlive, + "Path was not collected. The shared ScaleTransform is holding a strong reference to " + + "Path via its PropertyChanged event handler. Use WeakNotifyPropertyChangedProxy to fix."); + + GC.KeepAlive(sharedTransform); + } + + [Fact] + public void SharedGeometryAndTransform_DoNotKeepPathAlive() + { + var sharedGeometry = new PathGeometry + { + Figures = new PathFigureCollection + { + new PathFigure + { + StartPoint = new Point(0, 0), + Segments = new PathSegmentCollection + { + new LineSegment { Point = new Point(50, 50) } + } + } + } + }; + var sharedTransform = new ScaleTransform(2.0, 2.0) { CenterX = 25, CenterY = 25 }; + + var pathRef = CreatePathWithBoth(sharedGeometry, sharedTransform); + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + Assert.False(pathRef.IsAlive, + "Path was not collected. Shared PathGeometry and/or ScaleTransform are holding " + + "strong references to Path via event subscriptions. Use weak proxies to fix."); + + GC.KeepAlive(sharedGeometry); + GC.KeepAlive(sharedTransform); + } +}