Socket.CloseAsync Method

Asynchronously closes the Socket connection.

public virtual ValueTask CloseAsync(CancellationToken cancellationToken)
public virtual ValueTask CloseAsync(IProgress<SocketCloseProgress>? progress, CancellationToken cancellationToken)

Parameters

Parameter Description
progress An IProgress<SocketCloseProgress> object that receives progress notifications during the asynchronous close operation. This parameter can be null.
cancellationToken A CancellationToken to observe for cancellation requests. The default value is CancellationToken.None.

Remarks

The CloseAsync method initiates an asynchronous operation to close the Socket connection. This method is useful when you need to close a Socket without blocking the calling thread, allowing other operations to continue.

When CloseAsync is called, the Socket is put into a closing state. Any outstanding asynchronous send or receive operations are canceled. The underlying network connection is then gracefully closed.

The progress parameter can be used to monitor the progress of the close operation. This can be particularly useful for long-running close operations or for providing user feedback. The SocketCloseProgress object provides information about the current state of the close operation.

The cancellationToken parameter allows you to request cancellation of the close operation. If the token is signaled before the operation completes, the operation is canceled.

After CloseAsync completes successfully, the Socket is no longer usable for sending or receiving data. Attempting to use a closed Socket will result in an exception.

Exceptions

The following exceptions can be thrown by the CloseAsync method:

Requirements

The following table shows the available platform APIs for this method.

Platform Minimum Version
.NET Core 2.0
.NET Framework 4.6.1
.NET Standard 2.0
Windows Windows 10, version 1607
Windows Server Windows Server 2016
macOS macOS 10.13
Linux Ubuntu 16.04