BF2Statistics.Gamespy.Net.GamespyTcpSocket.StartAcceptAsync C# (CSharp) Method

StartAcceptAsync() protected method

Begins accepting a new Connection asynchronously
protected StartAcceptAsync ( ) : void
return void
        protected async void StartAcceptAsync()
        {
            // Fetch ourselves an available AcceptEventArg for the next connection
            SocketAsyncEventArgs AcceptEventArg;
            if (SocketAcceptPool.Count > 0)
            {
                try
                {
                    AcceptEventArg = SocketAcceptPool.Pop();
                }
                catch
                {
                    AcceptEventArg = new SocketAsyncEventArgs();
                    AcceptEventArg.Completed += (s, e) => PrepareAccept(e);
                }
            }
            else
            {
                // NO SOCKS AVAIL!
                AcceptEventArg = new SocketAsyncEventArgs();
                AcceptEventArg.Completed += (s, e) => PrepareAccept(e);
            }

            try
            {
                // Enforce max connections. If we are capped on connections, the new connection will stop here,
                // and retrun once a connection is opened up from the Release() method
                if (ConnectionEnforceMode == EnforceMode.BeforeAccept)
                    await MaxConnectionsEnforcer.WaitAsync();

                // Begin accpetion connections
                bool willRaiseEvent = Listener.AcceptAsync(AcceptEventArg);

                // If we wont raise event, that means a connection has already been accepted syncronously
                // and the Accept_Completed event will NOT be fired. So we manually call ProcessAccept
                if (!willRaiseEvent)
                    PrepareAccept(AcceptEventArg);
            }
            catch (ObjectDisposedException)
            {
                // Happens when the server is shutdown
            }
            catch (Exception e)
            {
                Program.ErrorLog.Write(
                    "ERROR: [GamespySocket.StartAccept] An Exception was thrown while attempting to recieve"
                    + " a conenction. Generating Exception Log"
                );
                ExceptionHandler.GenerateExceptionLog(e);
            }
        }