diff --git a/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs index d05fd43..ec19200 100644 --- a/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs @@ -102,6 +102,42 @@ public async Task WaitAsync_Generic_WithCancellationToken_RespectsToken() await act.Should().ThrowAsync(); } + [Theory] + [InlineData(null)] + [InlineData(0)] + [InlineData(-1)] + public async Task WaitAsync_Generic_NoTimeout_RespectsToken(int? timeoutMilliseconds) + { + // Arrange + var tcs = new TaskCompletionSource(); + using var cts = new CancellationTokenSource(); + TimeSpan? timeout = timeoutMilliseconds is { } ms ? TimeSpan.FromMilliseconds(ms) : null; + + // Act + var waitTask = tcs.Task.WaitBetterAsync(timeout, cts.Token); + cts.Cancel(); + + // Assert: bounded, so a regression fails instead of hanging + Func act = () => waitTask.WaitAsync(TimeSpan.FromSeconds(5)); + await act.Should().ThrowAsync(); + tcs.Task.IsCompleted.Should().BeFalse("only the wait is cancelled, not the awaited task"); + } + + [Fact] + public async Task WaitAsync_Generic_NullTimeout_CancelableTokenNotCancelled_ReturnsResult() + { + // Arrange + var tcs = new TaskCompletionSource(); + using var cts = new CancellationTokenSource(); + + // Act + var waitTask = tcs.Task.WaitBetterAsync(null, cts.Token); + tcs.SetResult(42); + + // Assert + (await waitTask).Should().Be(42); + } + #endregion #region WaitAsync (non-generic) tests @@ -185,6 +221,43 @@ public async Task WaitAsync_NonGeneric_WithCancellationToken_RespectsToken() await act.Should().ThrowAsync(); } + [Theory] + [InlineData(null)] + [InlineData(0)] + [InlineData(-1)] + public async Task WaitAsync_NonGeneric_NoTimeout_RespectsToken(int? timeoutMilliseconds) + { + // Arrange + var tcs = new TaskCompletionSource(); + using var cts = new CancellationTokenSource(); + TimeSpan? timeout = timeoutMilliseconds is { } ms ? TimeSpan.FromMilliseconds(ms) : null; + + // Act + var waitTask = tcs.Task.WaitBetterAsync(timeout, cts.Token); + cts.Cancel(); + + // Assert: bounded, so a regression fails instead of hanging + Func act = () => waitTask.WaitAsync(TimeSpan.FromSeconds(5)); + await act.Should().ThrowAsync(); + tcs.Task.IsCompleted.Should().BeFalse("only the wait is cancelled, not the awaited task"); + } + + [Fact] + public async Task WaitAsync_NonGeneric_NullTimeout_CancelableTokenNotCancelled_Completes() + { + // Arrange + var tcs = new TaskCompletionSource(); + using var cts = new CancellationTokenSource(); + + // Act + var waitTask = tcs.Task.WaitBetterAsync(null, cts.Token); + tcs.SetResult(); + + // Assert + await waitTask.WaitAsync(TimeSpan.FromSeconds(5)); + waitTask.IsCompletedSuccessfully.Should().BeTrue(); + } + #endregion #region Integration and edge case tests diff --git a/Plugin.BaseTypeExtensions/TaskExtensions.cs b/Plugin.BaseTypeExtensions/TaskExtensions.cs index 2616301..3f0a222 100644 --- a/Plugin.BaseTypeExtensions/TaskExtensions.cs +++ b/Plugin.BaseTypeExtensions/TaskExtensions.cs @@ -11,26 +11,28 @@ public static class TaskExtensions /// /// The type of the task result. /// The task to wait for. - /// The optional timeout duration. If null, zero, or negative, the method returns the original task (no timeout). + /// The optional timeout duration. If null, zero, or negative, no timeout is applied. /// A cancellation token to observe while waiting for the task to complete. /// - /// If timeout is null, zero, or negative: returns the original task. - /// Otherwise: returns a task that completes when the original task completes or when the timeout expires. + /// If timeout is null, zero, or negative: returns the original task when cannot be canceled, + /// otherwise a task that completes when the original task completes or when the token is canceled. + /// Otherwise: returns a task that completes when the original task completes, when the timeout expires, or when the token is canceled. /// /// Thrown when is null. /// Thrown when the task doesn't complete within the specified timeout. /// Thrown when the operation is canceled via the . /// /// This method provides a convenient way to add optional timeouts to any task. When no timeout is needed, - /// simply pass null and the original task is returned unchanged. This avoids the overhead of timeout monitoring - /// when it's not required. + /// simply pass null: the original task is returned unchanged unless the token can be canceled, in which case + /// the wait stays cancelable. Canceling the token only abandons the wait, the original task keeps running. /// public static Task WaitBetterAsync(this Task task, TimeSpan? timeout, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(task); if (!timeout.HasValue || timeout.Value <= TimeSpan.Zero) { - return task; + // No timeout, but the token must still be observed. Only skip WaitAsync when it can never fire. + return cancellationToken.CanBeCanceled ? task.WaitAsync(cancellationToken) : task; } // Cap very large timeouts to avoid ArgumentOutOfRangeException from Task.WaitAsync @@ -49,26 +51,28 @@ public static Task WaitBetterAsync(this Task task, TimeSpan? timeout, C /// Waits for the task to complete within an optional timeout period. /// /// The task to wait for. - /// The optional timeout duration. If null, zero, or negative, the method returns the original task (no timeout). + /// The optional timeout duration. If null, zero, or negative, no timeout is applied. /// A cancellation token to observe while waiting for the task to complete. /// - /// If timeout is null, zero, or negative: returns the original task. - /// Otherwise: returns a task that completes when the original task completes or when the timeout expires. + /// If timeout is null, zero, or negative: returns the original task when cannot be canceled, + /// otherwise a task that completes when the original task completes or when the token is canceled. + /// Otherwise: returns a task that completes when the original task completes, when the timeout expires, or when the token is canceled. /// /// Thrown when is null. /// Thrown when the task doesn't complete within the specified timeout. /// Thrown when the operation is canceled via the . /// /// This method provides a convenient way to add optional timeouts to any task. When no timeout is needed, - /// simply pass null and the original task is returned unchanged. This avoids the overhead of timeout monitoring - /// when it's not required. + /// simply pass null: the original task is returned unchanged unless the token can be canceled, in which case + /// the wait stays cancelable. Canceling the token only abandons the wait, the original task keeps running. /// public static Task WaitBetterAsync(this Task task, TimeSpan? timeout, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(task); if (!timeout.HasValue || timeout.Value <= TimeSpan.Zero) { - return task; + // No timeout, but the token must still be observed. Only skip WaitAsync when it can never fire. + return cancellationToken.CanBeCanceled ? task.WaitAsync(cancellationToken) : task; } // Cap very large timeouts to avoid ArgumentOutOfRangeException from Task.WaitAsync