我正在尝试在 C# 中构建一个套接字服务器,我遇到的一个问题是,当我将AsyncCallback传递给我的套接字的BeginReceive方法时,回调被调用得太快了,当我读取 IAsyncResult 的AsyncState属性时,我得到了 null。
我以为我已经通过添加“修复”了这个
.AsyncWaitHandle.WaitOne(100);
但问题仍然存在。谁能阐明我做错了什么?
我的代码如下(略):
private void Main(){
_listener.BeginAccept(new AsyncCallback(HandleConnection), null);
}
private void HandleConnection(IAsyncResult status)
{
SocketError socketRecieveError;
_connectionSocket = _listener.EndAccept(status);
_connectionSocket.BeginReceive(_receivedDataBuffer, 0, _receivedDataBuffer.Length, 0, out socketRecieveError,
new AsyncCallback(HandleHandshake), _connectionSocket.Available);
if(socketRecieveError != SocketError.Success)
_logger.Log("Socket error: " + socketRecieveError);
}
private void HandleHandshake(IAsyncResult status)
{
status.AsyncWaitHandle.WaitOne(1000);
int handshakeLength;
try
{
handshakeLength = Convert.ToInt32(status.AsyncState); // <--- BOOOM
}
catch (Exception ex)
{
_logger.Log(ex.Message);
}
..............
}