From 4a15e11c9cb117cfc42aea57d976a349c0acbfdb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 26 Apr 2023 16:19:55 +0200 Subject: [PATCH] Unregister PixelShaderEffect wrapper in finalizer --- .../PixelShaderEffect{T}.ReferenceTracking.cs | 26 ++++++++++++++++--- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs index dd5695ee..97ce8fa2 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs @@ -1,6 +1,12 @@ using System; using ComputeSharp.Interop; using System.Runtime.CompilerServices; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.Helpers; +#else +using ComputeSharp.D2D1.WinUI.Helpers; +#endif +using TerraFX.Interop.Windows; #if WINDOWS_UWP namespace ComputeSharp.D2D1.Uwp; @@ -41,15 +47,27 @@ partial class PixelShaderEffect } /// - void IReferenceTrackedObject.DangerousOnDispose() + unsafe void IReferenceTrackedObject.DangerousOnDispose() { + // When the effect is disposed, we also unregister it from the resource manager cache. This + // is analogous to what is done when manually unrealizing the effect (eg. when using a new + // device. Without this call, the resource manager would keep registered effects alive for + // the entire process duration, even if their original wrappers are gone (ie. collected). + if (this.d2D1Effect.Get() is not null) + { + ResourceManager.UnregisterWrapper((IUnknown*)this.d2D1Effect.Get()); + } + + // Release the native D2D objects that were set during realization this.canvasDevice.Dispose(); this.d2D1RealizationDevice.Dispose(); this.d2D1Effect.Dispose(); - // Also release all native resources for the used sources. - // The transform mapper and resource texture managers don't - // need to be disposed, as those could be shared between effects. + // Also release all native resources for the used sources. The transform mapper and + // resource texture managers don't need to be disposed, as those could be shared + // between effects. Note that SourceReference.Dispose() will only release the native + // resources (ie. D2D images and effects), but it will not also dispose the managed + // wrappers (ie. IGraphicsEffectSource objects), as those can be shared as well. for (int i = 0; i < Sources.Count; i++) { Sources.Storage[i].Dispose();