Should I manually dispose the socket after closing it?

北战南征 提交于 2019-12-18 05:27:09

问题


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.


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.




回答5:


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



回答6:


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.



来源:https://stackoverflow.com/questions/3601521/should-i-manually-dispose-the-socket-after-closing-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!