Garbage Collection

  • Thread starter Thread starter C# Learner
  • Start date Start date
C

C# Learner

class Foo
{
NetworkStream stream;

public void Bar()
{
TcpClient client = Something.GetTcpClient();
stream = client.GetStream();
}
}

Do I also need to hold a reference to /client/ to stop the object
referenced by /this.stream/ from being collected?

I'd assume so, but wanted to ask in case I'm missing something to do
with how TcpClient and NetworkStream work together here.
 
C# Learner said:
class Foo
{
NetworkStream stream;

public void Bar()
{
TcpClient client = Something.GetTcpClient();
stream = client.GetStream();
}
}

Do I also need to hold a reference to /client/ to stop the object
referenced by /this.stream/ from being collected?

I'd assume so, but wanted to ask in case I'm missing something to do
with how TcpClient and NetworkStream work together here.

You don't have to have a reference to the client to stop the stream
from being garbage collected, but you may well have to have a reference
to stop the stream from being closed due to the client being garbage
collected.
 
Jon said:
You don't have to have a reference to the client to stop the stream
from being garbage collected, but you may well have to have a reference
to stop the stream from being closed due to the client being garbage
collected.

Okay; thanks.
 
Back
Top