user1034912
user1034912

Reputation: 2267

C# Do we need to close TCPClient by using TCPClient.Close if it is no more used?

I'm making a program which sends data to many TCP listeners. If one of the TCP Sending channel is no more used, do we need to close it using TCPClient.close. What happens if we leave it open?

Thanks!

Upvotes: 3

Views: 2962

Answers (2)

Arjan Einbu
Arjan Einbu

Reputation: 13692

If you leave it open, the GC (Garbage Collector) will in time dispose of your object.

With TCPClient, the finalizer (the code run when the GC cleans up your object) has a call to Dispose(), which in turn closes the connection and frees any OS resources used by it.

You don't know WHEN the GC does it's cleaning up, so this approach is undeterministic. This probably isn't a problem with one or two open connections, but you may starve the system of resources if you open a huge number of these.

A good practice would be to always dispose TCPClients when you're done with them, and this can easily be accomplished with the using block. (As shown in Jon Skeets answer...)

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1504182

I wouldn't use Close explicitly - I'd just dispose it via a using statement:

using (TcpClient client = ...)
{
    // Use the client
}

What happens if we leave it open?

If neither side closes the connection, it'll be sitting there doing nothing, pointlessly.

If the other end closes the connection, I suspect you'll have a local connection in TIME_WAIT or something similar for a while; I don't know the exact details but it's not ideal.

The main point is that it may use up some system resources, and fundamentally it's not ideal. Is it going to cause your program to crash and your system to go crazy? Probably not - at least unless you're creating a huge number of these. It's still a good idea to dispose of anything with non-memory resources though.

Upvotes: 12

Related Questions