.NET Documentation

SocketAsyncEventArgs.Completed Event

Occurs when an asynchronous operation completes.

Syntax

public event EventHandler<SocketAsyncEventArgs> Completed;

Remarks

The Completed event is raised by the SocketAsyncEventArgs object when an asynchronous socket operation, initiated by a method such as AcceptAsync, ConnectAsync, DisconnectAsync, ReceiveAsync, ReceiveFromAsync, SendAsync, or SendToAsync, has completed.

The event handler you provide for the Completed event is called when the asynchronous operation finishes. This allows your application to process the results of the operation without blocking the calling thread.

The SocketAsyncEventArgs object passed to the event handler contains information about the completed operation, including any errors that occurred and the number of bytes transferred.

Event Data

The SocketAsyncEventArgs object passed to the event handler provides the following key properties:

Handling the Event

To handle the Completed event, you typically:

  1. Create an instance of SocketAsyncEventArgs.
  2. Register an event handler method with the Completed event.
  3. Initiate an asynchronous socket operation (e.g., Socket.ReceiveAsync).
  4. The event handler will be invoked automatically when the operation is complete.

Example

This example demonstrates how to handle the Completed event for a receive operation.

public class SocketAsyncHandler
{
    private Socket _socket;
    private SocketAsyncEventArgs _receiveEventArgs;
    private byte[] _buffer = new byte[1024];

    public SocketAsyncHandler(Socket listenSocket)
    {
        _socket = listenSocket;
        _receiveEventArgs = new SocketAsyncEventArgs();
        _receiveEventArgs.Completed += OnReceiveCompleted;
        _receiveEventArgs.SetBuffer(_buffer, 0, _buffer.Length);
    }

    public void StartReceiving()
    {
        bool willRaiseEvent = _socket.ReceiveAsync(_receiveEventArgs);
        if (!willRaiseEvent)
        {
            ProcessReceive(_receiveEventArgs);
        }
    }

    private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
    {
        ProcessReceive(e);
    }

    private void ProcessReceive(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
        {
            // Process received data
            string receivedData = System.Text.Encoding.ASCII.GetString(e.Buffer, e.Offset, e.BytesTransferred);
            Console.WriteLine($"Received: {receivedData}");

            // Prepare for the next receive operation
            e.SetBuffer(_buffer, 0, _buffer.Length); // Reset buffer
            bool willRaiseEvent = _socket.ReceiveAsync(e);
            if (!willRaiseEvent)
            {
                ProcessReceive(e);
            }
        }
        else if (e.SocketError == SocketError.ConnectionReset)
        {
            Console.WriteLine("Client disconnected.");
            // Clean up resources
            _socket.Close();
            _receiveEventArgs.Dispose();
        }
        else
        {
            Console.WriteLine($"Receive error: {e.SocketError}");
            // Handle other errors
            _socket.Close();
            _receiveEventArgs.Dispose();
        }
    }
}

See Also