Socket.ReceiveAsync problem

Posted by bartol on Stack Overflow See other posts from Stack Overflow or by bartol
Published on 2010-05-13T17:58:16Z Indexed on 2010/05/13 18:04 UTC
Read the original article Hit count: 2086

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about sockets