Rejkid
Rejkid

Reputation: 139

How many times can I call Socket.BeginAccept in C#

I am coming from Java programming language. I am just beginning my adventure with C# and .Net. I am creating a Server socket application using C# - based on Microsoft example (https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example). This is the sample code (from the page above):

while (true)
{
    // Set the event to nonsignaled state.  
    allDone.Reset();

    // Start an asynchronous socket to listen for connections.  
    Console.WriteLine("Waiting for a connection...");
    listener.BeginAccept(
        new AsyncCallback(AcceptCallback),
        listener);

    // Wait until a connection is made before continuing.  
    allDone.WaitOne();
}

... where allDone is a ManualResetEvent defined in the class scope. I can't understand what actually listener.BeginAccept does. For instance if I don't call method allDone.WaitOne() to wait until connection is made, then what would have happend - how many times the call to listener.BeginAccept method would execute (be successful) inside the loop until it starts waiting (or maybe it would crash eventually). I am probably missing something here. Can someone explain this to me please?

Regards,

Janusz

Upvotes: 0

Views: 531

Answers (1)

The intent here is for the AcceptCallback method to set the allDone event when a connection is accepted. The loop can then go on to accept another incoming connection while the just accepted one continues with whatever it needs to do.

You could have done other useful work on the listening thread after the call to BeginAccept, if you had any that made sense.

Oddly the documentation does not explicitly state (that I could find) what happens if you just repeatedly call BeginAccept without waiting, but my recommendation would be to not do that.

Upvotes: 2

Related Questions