如果在异步TCP或其他EAP模式中,成功处理程序具有对this
的引用,例如this.state
,理论上,当前实例应该有一个引用,因为this
被闭包自然保持在某个生成的对象范围内。因此,即使创建实例的作用域已经执行完毕,实例本身也不应该被垃圾回收?
我的代码类似于以下代码:
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)
{
// ...
// ...
}
}
}
执行它的代码可能如下所示:
public void DoExecuteCode()
{
new ATcpClient().Receive();
}
实例被垃圾回收导致整个Receive()失败了吗?
GCHandle
)。 - Ben VoigtGCHandle
。 - Ben Voigt