예제 #1
0
        private void StartAccept()
        {
            // Get a SocketAsyncEventArgs object to accept the connection.
            SocketAsyncEventArgs args;

            // Get it from the pool if there is more than one in the pool.
            // or make a new one.
            if (!_acceptArgsPool.TryPop(out args))
            {
                args            = new SocketAsyncEventArgs();
                args.Completed += SocketOperationCompleted;
            }

            // Socket.AcceptAsync begins asynchronous operation to accept the connection.
            var willRaiseEvent = _listenSocket.AcceptAsync(args);

            // Socket.AcceptAsync returns true if the I/O operation is pending, i.e. is working asynchronously.
            if (!willRaiseEvent)
            {
                // The code in this if (!willRaiseEvent) statement only runs
                // when the operation was completed synchronously. It is needed because
                // when Socket.AcceptAsync returns false,
                // it does NOT raise the SocketAsyncEventArgs.Completed event.
                // And we need to call ProcessAccept and pass it the SAEA object.
                // This is only when a new connection is being accepted.
                Task.Run(() => ProcessAccept(args));
            }

            _monitor.StartAccept();
        }