ARTICLE AD BOX
I've read in several places that one should never touch managed resources in the finalizer. Makes a lot of sense. But I am wondering about the assumptions that lie behind that advice.
What if the managed resource I want to touch from my class finalizer is not allocated with operator new() but rather from something like ArrayPool<byte>.Shared.Rent? In that case, I am supposed to return it to the pool with the ArrayPool.Return function.
I know I am supposed to ensure the object of my class is always disposed but the object in question here might be handed off to different threads. I cannot simply put a using statement in there or call Dispose() every time. I want to give it a finalizer to be sure the array is returned to the pool.
Here is an example of what I am talking about. Does the advice "never touch managed resources from a finalizer" still apply here?
public class CameraImage : IDisposable { public CameraImage(xiCam camera, int timeoutMs, int payloadSize) { Size = payloadSize; Data = ArrayPool<byte>.Shared.Rent(payloadSize); camera.GetImage(Data, timeoutMs); } public byte[]? Data { get; private set; } private int Size { get; } public void Dispose() { if ( _isDisposed ) return; _isDisposed = true; if (Data != null) { ArrayPool<byte>.Shared.Return(Data); Data = null } GC.SuppressFinalize(this); } ~CameraImage() { Dispose(); } }