[英]Cannot access a disposed object. Sockets C#
I use sockets, and when I try to close the socket, I get an我使用 sockets,当我尝试关闭套接字时,我得到一个
ObjectDisposedException: Cannot access a disposed object Object name: 'System.Net.Sockets.Socket'.
ObjectDisposedException:无法访问已处置的 object Object 名称:'System.Net.Sockets.Socket'。
exception.例外。
socket.Close();
socket.Shutdown(SocketShutdown.Both); <- exception
Why is this happening?为什么会这样? why does the garbage collector clean it out?
为什么垃圾收集器会清理它?
Remarks section of Socket.Close
documentation tells you Socket.Close
文档的备注部分告诉你
For connection-oriented protocols, it is recommended that you call
Shutdown
before calling theClose
method.对于面向连接的协议,建议您在调用
Close
方法之前调用Shutdown
。 This ensures that all data is sent and received on the connected socket before it is closed.这确保了在连接的套接字关闭之前,所有数据都在连接的套接字上发送和接收。
So, you should call Shutdown
before Close
, not the after所以,你应该在
Close
之前调用Shutdown
,而不是之后
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Close
is effectively synonymous with Dispose
in many cases.在许多情况下,
Close
实际上是Dispose
的同义词。 In the case of a socket, you should use Shutdown
before Close
/ Dispose
(or not at all).对于套接字,您应该在
Close
/ Dispose
之前使用Shutdown
(或根本不使用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.