How does the GC determines that it needs to deference a local object passed into a callback?
See the comments below on the need of disposing an object that is no longer referenced in an async callback.
private void SendStuff()
{
TcpClient tcpclient = new TcpClient();
//...connect, get stream and stuff
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), tcpclient);
//is there a chance the TcpClient will get GCed since it is out of scope of
//this method, even though it is referenced on the IAsyncResult
}
private void OnReadComplete(IAsyncResult ar)
{
TcpClient client = (TcpClient)ar.AsyncState;
// consume result
client.Dispose(); //is it really needed at this point?
}
I think in the particular case of TcpClient it will be overscope to do it as such
TcpClient tcpclient = new TcpClient();
private void SendStuff()
{
...
}
The TcpClient object will not be disposed when the reference tcpclient variable goes out of scope and not Disposed explicitly or in a using block while still referenced in BeginRead, is my assumption correct?