开发者

Should I manually dispose the socket after closing it?

Should I still开发者_JS百科 call Dispose() on my socket after closing it?

For example:

mySocket.Shutdown(SocketShutdown.Both);
mySocket.Close();
mySocket.Dispose(); // Redundant?

I was wondering because the MSDN documentation says the following:

Closes the Socket connection and releases all associated resources.


Calling Close internally calls Dispose so you don't need to call both. From .NET Reflector:

public void Close()
{
    if (s_LoggingEnabled)
    {
        Logging.Enter(Logging.Sockets, this, "Close", (string) null);
    }
    ((IDisposable)this).Dispose();
    if (s_LoggingEnabled)
    {
        Logging.Exit(Logging.Sockets, this, "Close", (string) null);
    }
}

If possible you should use the using pattern so that you always call Dispose regardless of any exceptions that might occur.


Close and Dispose are the same in this case. When Ms introduced the Dispose pattern in .Net 1, the Dispose word was not very discoverable. So the guideline was to add context specific keyword that will do the same functionality and will be more easily discoverable by users. Like Close for files and sockets.


By convention, you should always call Dispose on anything that implements IDisposable. You never know what other things it might do beyond the obvious.

And if you happen to use Reflector to see that, in fact, it currently isn't needed, you should not assume that the internal implementation may change at some point.

It never hurts to call Dispose. Just do it :)


It's generally regarded as a best practice by many to close IDisposable objects, because it makes the code clearer. Explicitly calling Dispose, though, is automatically done if you encapsulate the usage of the IDisposable in a using statement, as this page describes.


Let .NET invoke dispose:

using ( Socket mySocket = new Socket( ... ) ) {
  // Do stuff with socket, then bring it down nicely
}  // Dispose gets called returning the unmanaged system resources


You are right. The documentation is not clear since in the dispose method it is written that you should call Dispose() to clean the socket unmanaged resources, but on the other hand Close should do the same. I guess that Close calls Dispose or the contrary. The same behavior is supported by files so it is an educated guess.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜