SslStream.EndSecureChannel Method

Terminates an SSL/TLS connection. This method should be called after all data has been sent and received.

Syntax

public virtual void EndSecureChannel(
    AsyncCallback asyncResult
);
public virtual void EndSecureChannel(
    IAsyncResult asyncResult
);

Parameters

Name Type Description
asyncResult AsyncCallback
or
IAsyncResult
An IAsyncResult object returned by a call to an BeginInvoke method.

Remarks

Call this method to finish the asynchronous operation of establishing a secure channel.

After you call EndSecureChannel, the stream is no longer secure. You must call BeginAuthenticateAsClient or BeginAuthenticateAsServer to re-establish a secure channel.

This method should be called only after the asynchronous operation initiated by BeginSecureChannel has completed. If the asynchronous operation has not yet completed, this method will block until it completes.

Always call EndSecureChannel to free up resources and ensure proper termination of the secure connection.

Exceptions

Type Condition
ArgumentNullException asyncResult is null.
ArgumentException asyncResult did not return from a BeginSecureChannel method.
InvalidOperationException The stream is not secure or has already been closed.
ObjectDisposedException The SslStream has been disposed.

Example

The following example demonstrates how to call EndSecureChannel after initiating an asynchronous secure channel establishment.

using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

public class SslExample
{
    public async Task EstablishAndEndSecureChannelAsync()
    {
        TcpClient client = new TcpClient("example.com", 443);
        SslStream sslStream = new SslStream(
            client.GetStream(),
            false);

        try
        {
            // Begin initiating the secure channel
            IAsyncResult asyncResult = sslStream.BeginSecureChannel(null, null);

            // Wait for the operation to complete
            await Task.Factory.FromAsync(asyncResult, sslStream.EndSecureChannel);

            Console.WriteLine("Secure channel established.");

            // ... perform secure communication ...

            // After communication, terminate the secure channel
            // Note: Typically, you'd end authentication, not the secure channel directly after establishing it.
            // This example shows EndSecureChannel conceptually after some operation.
            // In a real scenario, you might call EndAuthenticateAsClient or EndAuthenticateAsServer.
            // Let's simulate ending the session after authentication.
            sslStream.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            client?.Close();
        }
    }
}

See Also