Quote:
The Dispose method’s main purpose is to clean up unmanaged resources, but it can also clean up managed resources.
If the class has only managed resources, it should implement IDisposable but it doesn’t need a destructor.
Question is why we "should" implement IDisposable. Garbage collector cleans up managed resources. Maybe for immediate cleanup?
|
Exactly. The garbage collector will eventually get around to cleaning up managed resources, but you don't know long that may take.
For an example, suppose an object opens and locks a file, and then the program stops using that object. The file may remain open and locked. Eventually the garbage collector will destroy the file stream, but other programs may want to use the file in the meantime. For instance, you might want to use File Explorer to delete it. In fact, other parts of the same program might want to use or delete the file.