Fix Little Memory Leak Risk

This commit is contained in:
copecone committed 2026-06-01 12:35:26 +09:00
1 parent 6bd4a8975e
commit bc7a7eca75
3 files changed
+47 -11

No files matched your search

+21 -6
View File
@@ -1,8 +1,8 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using ADOFAIRenderer.Core;
using ADOFAIRenderer.Util.FFmpeg;
using MelonLoader;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
@@ -16,6 +16,7 @@ namespace ADOFAIRenderer.Util
private const int InitialBufferSize = 16;
private readonly Stack<ReadbackRequestState> _statePool = new Stack<ReadbackRequestState>();
private readonly List<ReadbackRequestState> _allocatedStates = new List<ReadbackRequestState>();
private readonly object _poolLock = new object();
private bool _isInitialized;
private volatile bool _isDisposed;
@@ -27,13 +28,14 @@ namespace ADOFAIRenderer.Util
private void InitializePool()
{
lock (_poolLock)
{
if (_isInitialized) return;
for (var i = 0; i < InitialBufferSize; i++)
{
_statePool.Push(new ReadbackRequestState(this));
var state = new ReadbackRequestState(this);
_statePool.Push(state);
_allocatedStates.Add(state);
}
_isInitialized = true;
@@ -47,7 +49,17 @@ namespace ADOFAIRenderer.Util
lock (_poolLock)
{
state = _statePool.Count == 0 ? new ReadbackRequestState(this) : _statePool.Pop();
if (_statePool.Count == 0)
{
state = new ReadbackRequestState(this);
_allocatedStates.Add(state);
}
else
{
state = _statePool.Pop();
}
state.IsInFlight = true;
}
var bufferSize = texture.width * texture.height * 4; // RGBA = 4 channel
@@ -67,6 +79,7 @@ namespace ADOFAIRenderer.Util
lock (_poolLock)
{
state.IsInFlight = false;
if (_isDisposed)
{
state.Dispose();
@@ -146,11 +159,12 @@ namespace ADOFAIRenderer.Util
{
if (_isDisposed) return;
_isDisposed = true;
while (_statePool.Count > 0)
foreach (var state in _allocatedStates.Where(state => !state.IsInFlight))
{
var state = _statePool.Pop();
state.Dispose();
}
_statePool.Clear();
_allocatedStates.Clear();
_isInitialized = false;
}
}
@@ -161,6 +175,7 @@ namespace ADOFAIRenderer.Util
private readonly FrameReader _owner;
public long FrameIndex { get; private set; }
public NativeArray<byte> NativeBuffer;
public bool IsInFlight { get; internal set; }
public readonly Action<AsyncGPUReadbackRequest> CachedCallback;