Should I manually dispose the socket after closing

2019-01-26 02:38发布

Should I still 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.

6条回答
smile是对你的礼貌
2楼-- · 2019-01-26 03:28

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.

查看更多
相关推荐>>
3楼-- · 2019-01-26 03:31

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.

查看更多
你好瞎i
4楼-- · 2019-01-26 03:34

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 :)

查看更多
Juvenile、少年°
5楼-- · 2019-01-26 03:36

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.

查看更多
Bombasti
6楼-- · 2019-01-26 03:39

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.

查看更多
再贱就再见
7楼-- · 2019-01-26 03:43

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
查看更多
登录 后发表回答