Just wondering in case of Asynchronous TCP or other EAP pattern, if the success handler has a reference of this, e.g. this.state, in theory, there is a reference to current instance, as this is kept in some generated object scope by the closure nature. Thus the instance itself should not be garbage collected even the scope which create the instance is finished executing?
My code is similar to following:
public class ATcpClient
{
private ATcpState state = null;
private void Receive()
{
// create the callback here, in order to use in dynamic
AsyncCallback ReceiveCallback = delegate(IAsyncResult ar)
{
try
{
// Read data from the remote device.
this.state.BytesReceived = this.state.Socket.EndReceive(ar);
}
catch (Exception e)
{
// ...
}
};
try
{
this.state.Socket.BeginReceive(this.state.Buffer, 0, this.state.BufferSize, 0,
ReceiveCallback, null);
}
catch (Exception e)
{
// ...
// ...
}
}
}
code which execute it can look like:
public void DoExecuteCode()
{
new ATcpClient().Receive();
}
Would the instance been GC which cause the Receive() to fail as a whole?
That depends on how clever the compiler is.
In your case, yes,
thiswill definitely be kept alive by the delegate, for as long as the delegate lives.Let’s look at a case that will definitely NOT keep
thisalive:And then a case where compiler optimizations could affect the collection behavior:
The only remaining question is, what is the lifetime of that delegate? Is the pending operation a root, or do we just have a circular reference between the delegate, possibly
this,state,state.Socket, and the operation? If none of these are reachable from a root then the whole bunch can be finalized (which would close the socket, cancelling the operation).At least for some objects using the
BeginReceive/EndReceivepattern, the operation is NOT a rootIt looks like for your case (
Socket.BeginReceive), a root is created insideSystem.Net.Sockets.BaseOverlappedAsyncResult.PinUnmanagedObjects.