Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,14 @@ public partial interface IBluetoothRemoteDevice
/// <param name="timeout">The timeout for this operation</param>
/// <param name="cancellationToken">A cancellation token to cancel this operation.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
/// <remarks>
/// A call made while another connection attempt is in progress joins that attempt instead of starting a new one. It
/// returns when the attempt connects the device, and throws <see cref="DeviceFailedToConnectException" /> if the attempt
/// fails or is given up by its caller. Its own <paramref name="timeout" /> and <paramref name="cancellationToken" /> bound
/// only its wait: giving up does not cancel the attempt it joined.
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown when the device is already connected.</exception>
/// <exception cref="DeviceFailedToConnectException">Thrown if the connection attempt fails.</exception>
/// <exception cref="TimeoutException">Thrown if the connection attempt times out.</exception>
/// <exception cref="OperationCanceledException">Thrown when the operation is cancelled.</exception>
ValueTask ConnectAsync(ConnectionOptions? connectionOptions = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default);
Expand Down Expand Up @@ -132,6 +139,12 @@ public partial interface IBluetoothRemoteDevice
/// <param name="timeout">The timeout for this operation</param>
/// <param name="cancellationToken">A cancellation token to cancel this operation.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
/// <remarks>
/// A call made while another disconnection attempt is in progress joins that attempt instead of starting a new one. It
/// returns when the attempt completes, and throws <see cref="DeviceFailedToDisconnectException" /> if the attempt is given
/// up by its caller. Its own <paramref name="timeout" /> and <paramref name="cancellationToken" /> bound only its wait:
/// giving up does not cancel the attempt it joined.
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown when the device is not connected.</exception>
/// <exception cref="TimeoutException">Thrown if the disconnection attempt times out.</exception>
/// <exception cref="OperationCanceledException">Thrown when the operation is cancelled.</exception>
Expand Down
202 changes: 182 additions & 20 deletions Bluetooth.Core.Scanning/BaseBluetoothRemoteDevice.Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,14 @@ public bool IsConnecting
/// <inheritdoc />
public event EventHandler? Connecting;

// A plain field, not a bindable property: it is written under _attemptGate, and assigning a bindable property raises
// PropertyChanged synchronously, which would run subscribers inside the gate. IsConnecting is the observable state.
private TaskCompletionSource? _connectionTcs;

private TaskCompletionSource? ConnectionTcs
{
get => GetValue<TaskCompletionSource?>(null);
set => SetValue(value);
get => Volatile.Read(ref _connectionTcs);
set => Volatile.Write(ref _connectionTcs, value);
}

/// <summary>
Expand Down Expand Up @@ -155,16 +159,31 @@ public async virtual ValueTask ConnectAsync(ConnectionOptions? connectionOptions
DeviceIsAlreadyConnectedException.ThrowIfAlreadyConnected(this);
connectionOptions ??= new ConnectionOptions();

// Prevents multiple calls to ConnectAsync, if already starting, we merge the calls
if (ConnectionTcs is { Task.IsCompleted: false })
// Asynchronous continuations: a merged caller released by this attempt must not run its own code inside this one's cleanup.
var ownConnection = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
TaskCompletionSource? pendingConnection = null;
lock (_attemptGate)
{
// Prevents multiple calls to ConnectAsync, if already starting, we merge the calls
var current = ConnectionTcs;
if (current is { Task.IsCompleted: false })
{
pendingConnection = current;
}
else
{
ConnectionTcs = ownConnection; // Reset the TCS
Comment thread
Copilot marked this conversation as resolved.
Resolved
}
}

if (pendingConnection is not null)
{
LogMergingConnectionAttempts(Id);
await ConnectionTcs.Task.ConfigureAwait(false);
await WaitForMergedConnectionAsync(pendingConnection.Task, timeout, cancellationToken).ConfigureAwait(false);
return;
}

ConnectionTcs = new TaskCompletionSource(); // Reset the TCS
IsConnecting = true; // Set the connecting state to true
RefreshIsConnecting(); // Set the connecting state to true
Connecting?.Invoke(this, EventArgs.Empty);

try // try-catch to dispatch exceptions rising from start
Expand All @@ -190,7 +209,7 @@ public async virtual ValueTask ConnectAsync(ConnectionOptions? connectionOptions
// TimeoutException/OperationCanceledException directly on timeout/cancellation - it does
// NOT return normally past the deadline - so this line itself is where a timed-out
// connect attempt is detected, not the IsConnected check below.
await ConnectionTcs.Task.WaitBetterAsync(timeout, cancellationToken).ConfigureAwait(false);
await ownConnection.Task.WaitBetterAsync(timeout, cancellationToken).ConfigureAwait(false);

await NativeRefreshIsConnectedAsync(cancellationToken).ConfigureAwait(false);
if (!IsConnected)
Expand All @@ -215,6 +234,12 @@ public async virtual ValueTask ConnectAsync(ConnectionOptions? connectionOptions
try { await NativeDisconnectAsync(timeout: null, cancellationToken: CancellationToken.None).ConfigureAwait(false); }
catch { /* best-effort - we are already about to report the connection as failed */ }

// Callers merged into this attempt wait on its task, which no native callback completes
// once this attempt is over: end it here, after the cleanup above so that the
// disconnection callback it may raise is still absorbed by the pending attempt instead of
// being reported as an unexpected disconnection.
AbandonAttempt(ownConnection, new DeviceFailedToConnectException(this, innerException: e));

// Timeout/cancellation are documented, BCL-recognized outcomes of this method (see
// IBluetoothRemoteDevice.Connection.cs) - callers following the standard .NET cancellation
// idiom (catch (OperationCanceledException)) depend on the exact type surviving unwrapped.
Expand All @@ -229,8 +254,72 @@ public async virtual ValueTask ConnectAsync(ConnectionOptions? connectionOptions
}
finally
{
IsConnecting = false; // Set the connecting state to false
ConnectionTcs = null;
lock (_attemptGate)
{
// A caller released by AbandonAttempt, or one that arrived once this attempt had completed, may
// already have started the next attempt: only release what still belongs to this one.
if (ReferenceEquals(ConnectionTcs, ownConnection))
{
ConnectionTcs = null;
}
}

RefreshIsConnecting(); // Set the connecting state to false, unless the next attempt is already registered
}
}

// IsConnecting follows whether an attempt is registered. A claim or a release can land between reading that and writing
// the flag, so look again until the two agree.
private void RefreshIsConnecting()
{
bool connecting;
do
{
connecting = ConnectionTcs is not null;
IsConnecting = connecting;
}
while (connecting != (ConnectionTcs is not null));
}

/// <summary>
/// Waits for the connection attempt another caller owns. The merged caller's own
/// <paramref name="timeout" /> and <paramref name="cancellationToken" /> bound the wait, including the refresh of
/// the connection state that follows it; giving up does not cancel the owner's attempt.
/// </summary>
private async ValueTask WaitForMergedConnectionAsync(Task attempt, TimeSpan? timeout, CancellationToken cancellationToken)
{
var started = Stopwatch.GetTimestamp();
try
{
await WaitForAttemptAsync(attempt, timeout, cancellationToken).ConfigureAwait(false);

// A disconnection callback also completes the pending attempt, so completion alone does not
// mean the device is connected. The refresh gets what is left of the caller's timeout.
using var remaining = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
if (timeout is { } limit && limit != Timeout.InfiniteTimeSpan)
{
var left = limit - Stopwatch.GetElapsedTime(started);
remaining.CancelAfter(left > TimeSpan.Zero ? left : TimeSpan.Zero);
}

try
{
await NativeRefreshIsConnectedAsync(remaining.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && remaining.IsCancellationRequested)
{
throw new TimeoutException("The connection state could not be refreshed within the timeout.");
}

if (!IsConnected)
{
throw new DeviceFailedToConnectException(this);
}
}
catch (Exception e) when (e is not (DeviceFailedToConnectException or TimeoutException or OperationCanceledException))
{
// Same outcome as the owner: only genuinely opaque failures are normalized.
throw new DeviceFailedToConnectException(this, innerException: e);
}
}

Expand Down Expand Up @@ -259,10 +348,13 @@ public bool IsDisconnecting
/// <inheritdoc />
public event EventHandler? Disconnecting;

// A plain field for the same reason as _connectionTcs. IsDisconnecting is the observable state.
private TaskCompletionSource? _disconnectionTcs;

private TaskCompletionSource? DisconnectionTcs
{
get => GetValue<TaskCompletionSource?>(null);
set => SetValue(value);
get => Volatile.Read(ref _disconnectionTcs);
set => Volatile.Write(ref _disconnectionTcs, value);
}

/// <summary>
Expand Down Expand Up @@ -344,16 +436,32 @@ public async ValueTask DisconnectAsync(TimeSpan? timeout = null, CancellationTok

DeviceIsAlreadyDisconnectedException.ThrowIfAlreadyDisconnected(this);

// Prevents multiple calls to ConnectAsync, if already starting, we merge the calls
if (DisconnectionTcs is { Task.IsCompleted: false })
var ownDisconnection = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
TaskCompletionSource? pendingDisconnection = null;
lock (_attemptGate)
{
// Prevents multiple calls to DisconnectAsync, if already disconnecting, we merge the calls
var current = DisconnectionTcs;
if (current is { Task.IsCompleted: false })
{
pendingDisconnection = current;
}
else
{
DisconnectionTcs = ownDisconnection; // Reset the TCS
}
}

if (pendingDisconnection is not null)
{
// The merged caller's own timeout and cancellation token bound the wait; giving up does not
// cancel the owner's attempt.
LogMergingDisconnectionAttempts(Id);
await DisconnectionTcs.Task.ConfigureAwait(false);
await WaitForAttemptAsync(pendingDisconnection.Task, timeout, cancellationToken).ConfigureAwait(false);
return;
}

DisconnectionTcs = new TaskCompletionSource(); // Reset the TCS
IsDisconnecting = true; // Set the disconnecting state to true
RefreshIsDisconnecting(); // Set the disconnecting state to true
Disconnecting?.Invoke(this, EventArgs.Empty);

try // try-catch to dispatch exceptions rising from start
Expand All @@ -370,19 +478,46 @@ public async ValueTask DisconnectAsync(TimeSpan? timeout = null, CancellationTok
try
{
// Wait for OnDisconnection to be called
await DisconnectionTcs.Task.WaitBetterAsync(timeout, cancellationToken).ConfigureAwait(false);
await ownDisconnection.Task.WaitBetterAsync(timeout, cancellationToken).ConfigureAwait(false);
await ClearServicesAsync().ConfigureAwait(false);
await NativeRefreshIsConnectedAsync(cancellationToken).ConfigureAwait(false);
if (IsConnected)
{
throw new DeviceFailedToDisconnectException(this);
}
}
catch (Exception e)
{
// Callers merged into this attempt wait on its task, which no native callback completes
// once this attempt is over (timeout or cancellation here): end it so they stop waiting.
AbandonAttempt(ownDisconnection, new DeviceFailedToDisconnectException(this, innerException: e));
throw;
}
finally
{
IsDisconnecting = false; // Set the disconnecting state to false
DisconnectionTcs = null;
lock (_attemptGate)
{
// See ConnectAsync: only release what still belongs to this attempt.
if (ReferenceEquals(DisconnectionTcs, ownDisconnection))
{
DisconnectionTcs = null;
}
}

RefreshIsDisconnecting(); // Set the disconnecting state to false, unless the next attempt is already registered
}
}

// See RefreshIsConnecting.
private void RefreshIsDisconnecting()
{
bool disconnecting;
do
{
disconnecting = DisconnectionTcs is not null;
IsDisconnecting = disconnecting;
}
while (disconnecting != (DisconnectionTcs is not null));
}

/// <summary>
Expand All @@ -394,6 +529,33 @@ public async ValueTask DisconnectAsync(TimeSpan? timeout = null, CancellationTok

#endregion

#region Connection - Merged attempts

// Guards the decision to join or own an attempt and the release of ConnectionTcs/DisconnectionTcs, each one step. Only the
// attempt fields are touched under it: events are raised and flags are written outside.
private readonly object _attemptGate = new();

// Task.WaitAsync rather than WaitBetterAsync: the latter ignores the cancellation token when no timeout is given.
private static Task WaitForAttemptAsync(Task attempt, TimeSpan? timeout, CancellationToken cancellationToken)
{
return timeout is { } t ? attempt.WaitAsync(t, cancellationToken) : attempt.WaitAsync(cancellationToken);
}

/// <summary>
/// Ends a connect or disconnect attempt its owner is giving up on, so every caller merged into it
/// stops waiting. Does nothing when the attempt already completed.
/// </summary>
private static void AbandonAttempt(TaskCompletionSource attempt, Exception reason)
{
if (attempt.TrySetException(reason))
{
// Nobody may be merged into the attempt: read the fault so it is not reported as an unobserved task exception.
_ = attempt.Task.Exception;
}
}

#endregion

#region Connection - UnexpectedDisconnection

/// <inheritdoc />
Expand Down
Loading