I have the following code block, and it affects my program efficiency. The problem here is if the target host exists, everything is OK. But if it does exist, it takes too long to execute. Finally, I found out the “udp.Close()” occupies the most of execution time. If I does not invoke the close method, the efficiency is good.
Can anyone help me tell me what is the drawback if I do not invoke the close method?? Thank you very much.
{ // 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;
}
The drawback is that you’ll have a resource leak. You may be lucky enough that garbage collection happens often enough that it doesn’t demonstrate itself in your program, but why take the chance? From the documentation on
Close:Note, it talks of unmanaged resources. These will only be released by the
UdpClientrunning some code – it either does it inClose/Dispose, or it has to do it in itsFinalizemethod – nothing else will cause them to be released (assuming the program stays running).You may be able to hide the cost of the
Closeoperation by usingTask.Runto have it run on another thread – but you’d have to weigh up the cost of doing so.Or, to put it in more concrete terms – you say that you need this method to run many times. By not cleaning up your resources here, you would increase the chances that a subsequent call will fail completely because it cannot acquire the required resources (they’re all tied up in existing, non-
ClosedUdpClientinstances).And, as indicated in my comment, the following line is pointless:
Such code used to be of use in COM era VB, but it has no place in the .NET world.