I'm using sockets with Async Callbacks (both a server and a client), along with some Disposable (but synchronized) resources.
When I'm turning them off, I'm disposing them, and that's often cause my app to crash without throwing any exception. I'm afraid that I'm doing something wrong there (Well, duh...)
My questions are:
A. In what cases can a C# application crash without any notice (My assumption is due to disposal, or maybe Async attempts to use disposed objects, but I really have no idea).
B. Is there a way to find out exactly where the application crashes? It seems like when I'm actually debugging the code, everything is going as planned.
C. Could you please offer me a decent article or explanation how to create a good socket design? My current design is receiving alternating sizes of packets (4 bytes for command length (int32), and then packet of that specified length).
My Data Received Method:
private void OnDataReceived(IAsyncResult asyn)
{
SocketPacket packet = (SocketPacket)asyn.AsyncState;
try
{
ConnectionSocket client = GetConnection(packet.ClientID);
int length = client.Socket.EndReceive(asyn);
if (length == 0)
{
client.Dispose();
m_clients[packet.ClientID - 1] = null;
return;
}
packet.AlreadyRead += length;
if (packet.PacketDone)
{
if (client.ExpectToReceive == ExpectToReceive.MessageLength)
{
int cmdLength = BitConverter.ToInt32(packet.Data, 0);
packet.NextMessage(cmdLength);
client.ExpectData();
}
else
{
packet.NextMessage(4);
client.ExpectLength();
}
}
WaitForData(packet.ClientID, packet);
}
catch (ObjectDisposedException)
{
}
catch (SocketException se)
{
if (se.ErrorCode == 10054)
{
m_clients[packet.ClientID - 1] = null;
}
else
MessageBox.Show(se.Message);
}
}
My WaitForData Method:
private void WaitForData(int clientNumber, SocketPacket packet)
{
try
{
if (pfnWorkerCallBack == null)
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
Socket s = GetConnection(clientNumber).Socket;
s.BeginReceive(packet.Data, packet.AlreadyRead, packet.RemainingData,
SocketFlags.None, pfnWorkerCallBack, packet);
}
catch (ObjectDisposedException)
{
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
I'm pretty sure that the problem is somewhere around here... Can you point out maybe why?