Disposable Object
A base class that implements the IDisposable pattern correctly
Disposable Object ensures proper cleanup of both managed and unmanaged resources. It provides a structured way to handle resource disposal and helps prevent memory leaks in your Unity applications.
Features
Automatic disposal state tracking
Separate handling for managed and unmanaged resources
Protection against multiple disposals
Proper implementation of IDisposable pattern
GC optimization through SuppressFinalize
Usage Example
public class MyResourceHandler : DisposableObject
{
private FileStream _fileStream; // Managed resource
private IntPtr _nativeHandle; // Unmanaged resource
protected override void DisposeManagedResources()
{
// Dispose managed resources
_fileStream?.Dispose();
}
protected override void DisposeUnmanagedResources()
{
// Clean up unmanaged resources
if (_nativeHandle != IntPtr.Zero)
{
Marshal.FreeHGlobal(_nativeHandle);
_nativeHandle = IntPtr.Zero;
}
}
}
// Using the class
using (var handler = new MyResourceHandler())
{
// Work with resources
} // Automatically disposes when leaving scope
Override DisposeManagedResources
Override this method to clean up managed resources:
protected override void DisposeManagedResources()
{
// Dispose managed objects that implement IDisposable
_disposableField?.Dispose();
_listField?.Clear();
}
Override DisposeUnmanagedResources
Override this method to clean up unmanaged resources:
protected override void DisposeUnmanagedResources()
{
// Clean up unmanaged resources like:
// - Native memory allocations
// - File handles
// - System handles
}
Best Practices
Always use
using
statements when possibleCheck
Disposed
property before operations:
public void DoSomething()
{
if (Disposed) throw new ObjectDisposedException(nameof(MyResourceHandler));
// Method implementation
}
Don't call base methods when overriding:
protected override void DisposeManagedResources()
{
// Don't call base.DisposeManagedResources()
// Just implement your cleanup
}
Handle disposal in a deterministic manner:
public void CleanupResources()
{
if (!Disposed)
{
Dispose();
}
}
Important Considerations
Override
DisposeManagedResources
for IDisposable objectsOverride
DisposeUnmanagedResources
for native resourcesDon't throw exceptions from Dispose methods
Always check
Disposed
state in public methodsUse try-finally blocks for critical cleanup operations
Last updated