Definition - What does Dispose mean?
In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections. Dispose improves performance and optimizes memory by releasing unmanageable objects and scarce resources, like Graphics Device Interface (GDI) handles used in applications with restricted Windows space.
The Dispose method, provided by the IDisposable interface, implements Dispose calls. The Dispose pattern is designed for timely and predictable cleanup, prevention of temporary memory leaks and disposal of resources.
Techopedia explains Dispose
The .NET framework facilitates garbage collection (GC), manages object memory and resources and reclaims invalid object memory references by invoking Finalize - a non-deterministic method. The Dispose method controls the lifetime of object memory instances and provides explicit memory cleanup control, versus Finalize's implicit memory cleanup. Dispose may be invoked even when other memory object instances exist, whereas Finalize may only be invoked after the last memory object is destroyed.
Dispose method rules are as follows:
- Used for unmanaged resources requiring immediate release after use.
- If Dispose is not called, the Finalize method should be implemented.
- After calling the Dispose method, the GC.SuppressFinalize method must be called to avert the Finalize method and avoid unnecessary GC.
- Exceptions should be carefully handled if the Dispose method is invoked more than once. If resources are disposed, any instance method may throw the ObjectDisposedException.
- An object with a previously called Dispose method may not be reused.
- Dispose is recommended only for the management of native resource objects and Component Object Model (COM) objects exposed to the .NET Framework.
- Dispose may not be concurrently invoked from multiple threads, due to unpredictable results.
- Value types should not be created as disposable types or with unmanaged resource members.
- When using unmanaged resources, it is considered best practice to apply the source code's Using statement, which automatically invokes the object's Dispose method after completing the object code.