Skip to content

How to stop running async method

Alex

Asked May 1, 2008, 6:01 AM EDT4 answers
Share
LinkedInX
Hello, I'm writting a server using async sockets. The server must listen for incoming data on multiple sockets. That means I have multiple calls to the Socket.ReceiveAsync(). The problem arrises when I want to shutdown the server. How I can I stop these ReceiveAsync() methods before I close the sockets ? If I just call the Close() function on a socket I get an exception: Cannot access a disposed socket. after Close() is executed. I can catch the exception but I think there should be a cleaner way to do this.

4 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    You should just be able to call the Socket.EndReceive() method and it will end the asynchronous receive operation.
    0
  • 0
    It may work but where do I get the IAsyncResult argument from, in order to call Socket.EndReceive(IAsyncResult asyn) ?
    0
  • 0
    You should be able to just pass null as that parameter and it should work, last I remember it did... Im a multithreader so Im a little dusty on making ssync method calls :(
    0
  • 0
    Already tried that but it doesn't work with null args.
    I've played a little and noticed that calling the Dispose method of the SocketAsyncEventArgs passed to the socket works. It goes something like this:

    SocketAsyncEventArgs arg;
    //code to set up arg
    socket.ReceiveAsync(arg);
    //do other stuff
    arg.Dispose();

    No exceptions are thrown and the sockets stop waiting for data. Is this ok ?
    0