replace WeakReference with weak GCHandle

pull/53/head
cosmonaut 2023-11-20 15:18:06 -08:00
parent 36a88afe52
commit b2a0ca3515
2 changed files with 14 additions and 12 deletions

View File

@ -2,6 +2,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using RefreshCS;
namespace MoonWorks.Graphics
@ -22,7 +23,7 @@ namespace MoonWorks.Graphics
public bool IsDisposed { get; private set; }
private readonly HashSet<WeakReference<GraphicsResource>> resources = new HashSet<WeakReference<GraphicsResource>>();
private readonly HashSet<GCHandle> resources = new HashSet<GCHandle>();
private FencePool FencePool;
internal GraphicsDevice(
@ -338,7 +339,7 @@ namespace MoonWorks.Graphics
return (TextureFormat) Refresh.Refresh_GetSwapchainFormat(Handle, window.Handle);
}
internal void AddResourceReference(WeakReference<GraphicsResource> resourceReference)
internal void AddResourceReference(GCHandle resourceReference)
{
lock (resources)
{
@ -346,7 +347,7 @@ namespace MoonWorks.Graphics
}
}
internal void RemoveResourceReference(WeakReference<GraphicsResource> resourceReference)
internal void RemoveResourceReference(GCHandle resourceReference)
{
lock (resources)
{
@ -377,11 +378,12 @@ namespace MoonWorks.Graphics
{
lock (resources)
{
foreach (var weakReference in resources)
foreach (var resource in resources)
{
if (weakReference.TryGetTarget(out var target))
var target = resource.Target;
if (target is IDisposable disposable)
{
target.Dispose();
disposable.Dispose();
}
}
resources.Clear();

View File

@ -1,4 +1,5 @@
using System;
using System.Runtime.InteropServices;
namespace MoonWorks.Graphics
{
@ -10,14 +11,14 @@ namespace MoonWorks.Graphics
public bool IsDisposed { get; private set; }
protected abstract Action<IntPtr, IntPtr> QueueDestroyFunction { get; }
internal WeakReference<GraphicsResource> weakReference;
internal GCHandle selfReference;
public GraphicsResource(GraphicsDevice device, bool trackResource = true)
{
Device = device;
weakReference = new WeakReference<GraphicsResource>(this);
Device.AddResourceReference(weakReference);
selfReference = GCHandle.Alloc(this, GCHandleType.Weak);
Device.AddResourceReference(selfReference);
}
internal GraphicsResourceDisposalHandle CreateDisposalHandle()
@ -36,10 +37,9 @@ namespace MoonWorks.Graphics
if (Handle != IntPtr.Zero)
{
QueueDestroyFunction(Device.Handle, Handle);
Device.RemoveResourceReference(weakReference);
weakReference.SetTarget(null);
Device.RemoveResourceReference(selfReference);
selfReference.Free();
weakReference = null;
Handle = IntPtr.Zero;
}