views:

86

answers:

2

A new instance of a TcpClient connects to a remote host. Its NetworkStream is retrieved and stored. Do I have to store the TcpClient itself as well to make sure it is not garbage collected?

In case you're going to answer "You have to store it to be able to dispose it": In my specific case, the TcpClient is usually living for a long time (app lifetime), so disposing it is not really a must. However, I agree that, in general, it has to be stored just to be able to call Dispose.

+1  A: 

If the object is not referenced, it will be garbage collected eventually, that will make your NetworkStream unusable. You need to keep the reference of that TcpClient object as long as you wish to use it.

cornerback84
Now I'm confused - Mike is basically saying the opposite. Who's right? :)
mafutrct
If he has checked it then he is right. I though that TcpClient's finalizer invalidates the NetworkStream. But as he said, you cannot rely on that. Better keep the reference.
cornerback84
+2  A: 

The NetworkStream will not be deleted if it's still referenced. The garbage collector only cleans up objects that are no longer referenced - it doesn't really know anything about the objects it has to collect, it just tracks references.

However, you may find that TcpClient has a finalizer that will invalidate the stream if the TcpClient is collected. It's probably safer to keep a reference to the TcpClient as well. (As far as I can see from the source code, the finalizer doesn't currently do this, but there's no guarantee that it won't in the future.)

Mike Dimmick
+1 Thanks, useful info
mafutrct