Socket.ReceiveAsync problem
- by bartol
Hi,
I have a problem using SocketAsyncEventArgs model with .net sockets.
Everything works great until the moment that the server wishes to close a client connection.
I use following code for this:
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch
{
} // throws if client process has already closed
finally
{
socket.Close();
}
socket = null;
Each connection is using two SocketAsyncEventArgs (one for send and one for receive) and after closing the connection they are returned to a pool from which they can be later reused. And here the problem starts, because when another connection is established and receive args are reused from the pool we get an exception:
System.InvalidOperationException: "An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance.";
at System.Net.Sockets.SocketAsyncEventArgs.StartOperationCommon(Socket socket)
at System.Net.Sockets.Socket.ReceiveAsync(SocketAsyncEventArgs e)
I've done some debugging and it appears that the connection closing code from the beginning of the question does not cancel Socket.ReceiveAsync operation that is in progress when the connection is closed. I've tried many combinations of Shutdown, Disconnect and Linger options for the socket but nothing worked.
Any suggestions?
Thanks