0

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?

Kwyjibo
  • 53
  • 1
  • 5
  • The .NET GC does not use reference counting (as your question seems to imply), you might want to read up on how the GC works. – CodingGorilla Mar 24 '16 at 16:23
  • @CodingGorilla i have stumbled upon this answer which is similar to what i described above http://stackoverflow.com/a/4434127/1449060 – Kwyjibo Mar 24 '16 at 18:26

1 Answers1

0

The object will not be disposed when it goes out of scope, but then it is unreachable, wich will not happen before the OnReadComplete completes.

For the BeginRead method to call OnReadComplete passing the client as a parameter it must save the client somewhere, it doesn't matter where, but is in someplace where it can reach later to pass it back to the OnReadComplete, so the object never becomes unreachable.

C# have another directive to dispose objects when they goes out of scope, it is the "using" directive, if you used it, this code would throw na ObjectDisposedException.

EduardoS
  • 199
  • 1
  • 3