System.Net.Sockets.Socket.ReceiveAsync C# (CSharp) Method

ReceiveAsync() public method

public ReceiveAsync ( SocketAsyncEventArgs e ) : bool
e SocketAsyncEventArgs
return bool
        public bool ReceiveAsync(SocketAsyncEventArgs e)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
            bool retval;

            if (CleanedUp)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }

            // Prepare for the native call.
            e.StartOperationCommon(this);
            e.StartOperationReceive();

            // Local vars for sync completion of native call.
            SocketFlags flags;
            int bytesTransferred;
            SocketError socketError;

            // Wrap native methods with try/catch so event args object can be cleaned up.
            try
            {
                socketError = e.DoOperationReceive(_handle, out flags, out bytesTransferred);
            }
            catch
            {
                // Clear in-use flag on event args object. 
                e.Complete();
                throw;
            }

            // Handle completion when completion port is not posted.
            if (socketError != SocketError.Success && socketError != SocketError.IOPending)
            {
                e.FinishOperationSyncFailure(socketError, bytesTransferred, flags);
                retval = false;
            }
            else
            {
                retval = true;
            }

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
            return retval;
        }

Usage Example

        public void Receive(object obj)
        {
            string received = "";

            while (isok)
            {
                socketReceiveArgs = new SocketAsyncEventArgs();
                socketReceiveArgs.SetBuffer(new byte[5120], 0, 5120);
                socketReceiveArgs.Completed += SocketReceiveArgs_Completed;
                try
                {
                    done.Reset();

                    if (tcpc.ReceiveAsync(socketReceiveArgs))
                    {
                        done.WaitOne();
                    }

                    System.Threading.Thread.Sleep(50);
                }
                catch (Exception e)
                {
                }
            }
        }
All Usage Examples Of System.Net.Sockets.Socket::ReceiveAsync