Skip to content

[BUG] WaitBetterAsync ignores the cancellation token when there is no timeout #62

Closed

Description

@framinosona

Bug Description

TaskExtensions.WaitBetterAsync(this Task, TimeSpan?, CancellationToken) and the Task<T> overload ignore the cancellation token when there is no timeout. With timeout null, zero or negative they return the original task unchanged, so a token that is cancelled while the task is pending has no effect. The cancellationToken parameter is documented as "A cancellation token to observe while waiting for the task to complete".

Found with a small console while working on Plugin.Bluetooth: a pending task, WaitBetterAsync(null, token), then token cancelled; the returned task kept pending until the task itself completed. With a timeout, Task.WaitAsync(timeout, token) is used and the token works. Plugin.Bluetooth's own waits go through this method (for example the scanner's wait for the platform's stop signal), so StopScanningAsync(cancellationToken: token) without a timeout cannot be cancelled either.

Only the Task and Task<T> overloads were read; the SemaphoreSlim overloads were not checked.

Code to Reproduce

var pending = new TaskCompletionSource().Task;
using var cts = new CancellationTokenSource();
var wait = pending.WaitBetterAsync(null, cts.Token);
cts.Cancel();
await Task.Delay(200);
Console.WriteLine(wait.IsCompleted); // False; with a timeout it is True (cancelled)

Expected Behavior

Return the original task only when the token cannot be cancelled (!cancellationToken.CanBeCanceled); otherwise use task.WaitAsync(cancellationToken) so the token is observed with and without a timeout. Document the behaviour, and add a test for "null timeout, token cancelled".

Environment

  • Code at main (aeac49d)

Activity

  1. added
    bug
    on Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions