C# Accepting sockets in async fasion - best practices

Posted by psulek on Stack Overflow See other posts from Stack Overflow or by psulek
Published on 2010-05-04T15:03:28Z Indexed on 2010/05/04 15:08 UTC
Read the original article Hit count: 271

Filed under:
|
|

What is the best way to accept new sockets in async way.

First way:

while (!abort && listener.Server.IsBound)
{  
  acceptedSocketEvent.Reset();  
  listener.BeginAcceptSocket(AcceptConnection, null);  

  bool signaled = false;  
  do  
  {  
     signaled = acceptedSocketEvent.WaitOne(1000, false);
  } while (!signaled && !abort && listener.Server.IsBound);
}

where AcceptConnection should be:

private void AcceptConnection(IAsyncResult ar)
{
    // Signal the main thread to continue.
    acceptedSocketEvent.Set();

    Socket socket = listener.EndAcceptSocket(ar);
    // continue to receive data and so on...
    ....
}

or Second way:

listener.BeginAcceptSocket(AcceptConnection, null);
while (!abort && listener.Server.IsBound)
{  
   Thread.Sleep(500);
}

and AcceptConnection will be:

private void AcceptConnection(IAsyncResult ar)
{
    Socket socket = listener.EndAcceptSocket(ar);
    // begin accepting next socket
    listener.BeginAcceptSocket(AcceptConnection, null);
    // continue to receive data and so on...
    ....
}

What is your prefered way and why?

© Stack Overflow or respective owner

Related posts about c#

Related posts about sockets