C#中Socket关闭 Close、Dispose、Shutdown、Disconnect
An answer on StackOverflow made me think I have finally reached some glimpse of an understanding. Then I went testing for a bit and here's the summary of a newbie's view. Please correct me if I'm wrong because this is based on inference, not expertise.
Shutdown
Shutdown
disables the Send
and/or Receive
methods, depending on the provided argument. It doesn't disable the underlying protocol handling and it never blocks.
If Send
is disabled, it also queues up a zero-byte send packet into the underlying send buffer. When the other side receives this packet, it knows that your socket will no longer send any data.
If Receive
is disabled, any data the other side might be trying to send will be lost.
If Receive
is disabled without disabling Send
, it just prevents the socket from receiving data. Since no zero-byte packet will be sent, the other side won't know anything about it until it tries to send something, and only if the socket's protocol requires acknowledging.
Disconnect
First, Disconnect
does the equivalent of Shutdown(SocketShutdown.Both)
.
Then it blocks, waiting for two things:
- For all the queued-up send data to be sent.
- For the other side to acknowledge the zero-byte packet (if applicable to the underlying protocol).
If you call Disconnect(false)
, system resources will be freed.
Close
Close
frees system resources. May abruptly stop sending queued-up data. If called with the argument, will wait for the data to be sent, but only up to the specified timeout.
Dispose
Dispose
is same as the Close
overload without the timeout argument. To be more precise, Close
without timeout is the same as Dispose
.
If you use the using
block on the socket, it will automatically call Dispose
.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决