0

In my class I have unmanaged objects in managed collection (pendingFramesBuffer). I need to implemented IDisposable interface.

My question: Where I need to clear pendingFramesBuffer collection? In the if (disposing) {...} condition or not.

public class Example : IDisposable
{
    // unmanaged pointer in managed collection
    private BlockingCollection<IntPtr> pendingFramesBuffer = new BlockingCollection<IntPtr>();

    /// SOME CODE TO FILL pendingFramesBuffer COLLECTION

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
        
            }

            // CLEAR pendingFramesBuffer COLLECTION
            while (pendingFramesBuffer != null && pendingFramesBuffer.Count > 1)
            {
                var tookFrameBuffer = pendingFramesBuffer.Take();
                Marshal.FreeHGlobal(tookFrameBuffer);
            }

            this.disposed = true;
        }
    }

    ~Example()
    {
        Dispose(false);
    }
}
  • 1
    Can you use `SafeHandle` instead of `IntPtr`? – David Jones Jun 24 '21 at 20:21
  • Using `SafeHandle` would be much better. It lets you avoid the finalizer and the `disposing` flag. The `disposing` flag is there so you can avoid disposing objects that themselves are managed and have finalizers; it doesn't apply to your unmanaged objects and so you would put the release of the unmanaged resources _outside_ the `disposing` check. See duplicate for those details and more. If you switch to `SafeHandle`, you can get rid of the finalizer altogether, as well as the `disposing` flag and any code executed only within that check. But you'll still release your unmanaged memory. – Peter Duniho Jun 24 '21 at 20:23
  • Hello! Thanks for advice, I tried to use the SafeHandle, but it's not suite for me. I work with frames, and if I don't clear buffer by yourself the memory very fast fulled, it has time to fill up to 7-8 GB before GC cleans it. – Валентин Никин Jun 25 '21 at 08:19

0 Answers0