我有一个使用带有开始/结束设计模式的异步套接字的应用程序。
每当我收到一个新连接时,我都会创建一个对象并将其存储在一个集合中。该对象还在其自身中存储套接字连接,并将在开始方法“对象状态”中传递。
现在服务器正在异步运行、发送、接收等,在任何给定时间为一个对象执行多个代码路径。
我不明白的是:如果我调用一个传入当前对象和另一个线程的函数,该对象刚刚被释放,那么当前在执行代码中的另一个对象会发生什么。
编辑:
例如)如果您查看调用 doSomthing() 的 ReadDataCallback()。如果它要使用我的“设备”对象调用 doSomthing(),但相应的设备在 SendCallback() 中有异常。即将调用 doSomthing() 的设备对象处于什么状态?
这是一个代码示例。
void waitForData(MyDevice device)
{
try
{
if (device.SocketState.IsSSL)
{
device.SocketState.sslStream.BeginRead(device.SocketState.DataBuffer, 0, device.SocketState.DataBuffer.Length, m_readDataCallback, device);
}
else
{
device.SocketState.DeviceSocket.BeginReceive(device.SocketState.DataBuffer, 0, device.SocketState.DataBuffer.Length, SocketFlags.None, m_readDataCallback, device);
}
}
catch (SocketException se)
{
DisconnectAndRemove(device);
}
}
public void ReadDataCallback(IAsyncResult ar)
{
MyDevice device = (MyDevice)ar.AsyncState;
try
{
Queue<kustompacket> qps = null;
int iRx = 0;
if (device.SocketState.IsSSL)
{
iRx = device.SocketState.sslStream.EndRead(ar);
if (iRx == 0)
{
DisconnectAndRemove(device);
}
else if (iRx > 0)
{
device.CircularBuff.Add(iRx, device.SocketState.DataBuffer);
qps = device.CircularBuff.ReadPackets();
doSomthing(device);
}
}
else
{
if (device.SocketState.DeviceSocket != null)
{
if (device.SocketState.DeviceSocket.Connected)
{
// Read data from the client socket.
iRx = device.SocketState.DeviceSocket.EndReceive(ar);
if (iRx == 0)
{
DisconnectAndRemove(device);
}
else if (iRx > 0)
{
device.CircularBuff.Add(iRx, device.SocketState.DataBuffer);
qps = device.CircularBuff.ReadEncryptedPackets(device.SocketState.SessionID);
doSomthing(device);
}
}
}
}
if (qps != null)
{
MyDelegate meh = new MyDelegate(HandleDataReceived);
meh.BeginInvoke(device, qps, null, null);
}
if (iRx != 0)
{
waitForData(device);
}
}
catch (ObjectDisposedException ode)
{
//Socket has been closed
//DisconnectAndRemove(device);
}
catch (SocketException se)
{
//if (se.ErrorCode == 10054) // Error code for Connection reset by peer
//{
DisconnectAndRemove(device);
//}
}
catch (Exception ex)
{
DisconnectAndRemove(device);
}
}
public void SendCallback(IAsyncResult ar)
{
MyDevice device = (MyDevice)ar.AsyncState;
try
{
// Complete sending the data to the remote device.
if (device.SocketState.IsSSL)
{
device.SocketState.sslStream.EndWrite(ar);
}
else
{
int bytesSent = device.SocketState.DeviceSocket.EndSend(ar);
}
device.ResetAge();
}
catch (SocketException se)
{
DisconnectAndRemove(device);
}
catch (Exception ex)
{
}
if (device.SocketState.IsSSL)
{
device.Write();
}
}