What does the Dispose method do in C#?

.net, c#

Solution

Your assumption that the code you found "invokes the Garbage Collection to release" the underlying resource is not correct.

At the core, your message uses a `Stream`. `SuppressFinalize` is not what you are looking for (if you are interested, it just sets a flag for the GC, and more details are explained here). But, you are really looking for the implementation of `Dispose` of the stream that you are using. A stream allows you to read or write data to/from some source or destination.

There are many different kinds of Streams. All a stream does is wrapping some sort of resource, such as files on disk, network, on a web server, mail server, on printers, in memory or pretty much any sort of data resource a computer has to offer. So, the `Dispose` method usually just "closes" the resource (it closes, for example, the file or network connection that the stream used).

Most streams open/read/write/close the underlying resource by placing system calls to communicate with the Operating System who is the guy in charge of maintaining your computer's resources. If you are interested in the low-level details of that, you might want to read a good book or take an online course on Operating Systems.

Problem

When I write a mail delivery service, I find the 'Dispose()' function: ``` private void InnerDisposeMessage(MailMessage message) { if (message != null) { if (message.AlternateViews.Count > 0) { message.AlternateViews.Dispose(); } message.Dispose(); message = null; } } ``` And I track to the `Dispose()` function(`message.AlternateViews.Dispose();)`, here it is: ``` public void Dispose() { if (!this.disposed) { foreach (AlternateView view in this) { view.Dispose(); } base.Clear(); this.disposed = true; } } ``` And I track to the view.Dispose() function, here it is: ``` protected virtual void Dispose(bool disposing) { if (disposing && !this.disposed) { this.disposed = true; this.part.Dispose(); } } ``` And I track to the this.part.Dispose(); function, here it is: ``` public void Dispose() { if (this.stream != null) { this.stream.Close(); } } ``` And I track to the stream: ``` public virtual void Close() { this.Dispose(true); GC.SuppressFinalize(this); } ``` and the SuppressFinalize: ``` public static void SuppressFinalize(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } _SuppressFinalize(obj); } ``` But how the resource to be released? I just understand to invoke the Garbage Collection to release, but how? I know this question is not easy to understand, but I just want to try! What the GC.SuppressFinalize(this) function do?

Original source

Related problems