如果我不调用UdpClient.Close()方法有什么缺点?

我有以下代码块,它会影响我的程序效率。 这里的问题是如果目标主机存在,一切正常。 但如果确实存在,执行时间太长。 最后,我发现“udp.Close()”占用了大部分执行时间。 如果我不调用close方法,效率很高。

任何人都可以帮我告诉我,如果我不调用close方法有什么缺点? 非常感谢你。

{ // This is my code block, I need to execute it many many times. string ipAddress = Dns.GetHostAddresses("joe-pc").FirstOrDefault().ToString(); UdpClient udp = new UdpClient(ipAddress, Port); udp.Send(msg, msg.Length); udp.Close(); udp = null; } 

缺点是你会有资源泄漏。 你可能很幸运,垃圾收集经常发生,它不会在你的程序中展示自己,但为什么要抓住机会呢? 从Close文档:

Close禁用基础Socket并释放与UdpClient关联的所有托管和非托管资源。

请注意,它涉及非托管资源。 这些只会由运行一些代码的UdpClient释放 – 它要么在Close / Dispose ,要么必须在Finalize方法中执行 – 没有其他任何东西会导致它们被释放(假设程序保持运行)。

可以通过使用Task.Run让它在另一个线程上运行来隐藏Close操作的成本 – 但是您必须权衡这样做的成本。


或者,更具体地说 – 你说你需要这种方法多次运行。 通过不清理您的资源,您将增加后续调用完全失败的可能性,因为它无法获取所需的资源(它们全部都绑定在现有的非Close d UdpClient实例中)。


而且,正如我的评论所示,以下几行毫无意义:

 udp = null; 

这些代码曾经在COM时代的VB中使用,但它在.NET世界中没有地位。

Close()禁用底层Socket并释放与UdpClient关联的所有托管和非托管资源。 如果你没有关闭,那么它不会禁用和取消分配像ur port和ipaddress这样的资源

您可以使用BeginSend而不是使用Send ,然后在您的回调中处理exception,当您尝试关闭时,如果这实际上是问题吗?

当dns记录发生变化时,您可能会使用不同的ip地址来定位joe-pc,但是每次发送都会重复使用相同的UdpClient。 只要记住在完成所有操作后关闭()它。

使用

 // // Summary: // Sends a UDP datagram to a specified port on a specified remote host. // // Parameters: // dgram: // An array of type System.Byte that specifies the UDP datagram that you intend // to send represented as an array of bytes. // // bytes: // The number of bytes in the datagram. // // hostname: // The name of the remote host to which you intend to send the datagram. // // port: // The remote port number with which you intend to communicate. // // Returns: // The number of bytes sent. // public int Send(byte[] dgram, int bytes, string hostname, int port); 

并跳过dns查找。

我知道这已经有一段时间了,但今天我偶然发现了这个问题并希望补充:

UDP = NULL;

并非毫无意义的imho。 在某些情况下,您可以在内存分析器中看到,如果您未将其设置为null,则您的实例仍然可用。