Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit e9bf0ca

Browse files
committed
Merge pull request #2439 from stephentoub/unwrap_notcanceled
Fix small discrepancy in TaskExtensions.Unwrap
2 parents 75a2a1b + dcfa285 commit e9bf0ca

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/System.Threading.Tasks/src/System/Threading/Tasks/TaskExtensions.CoreCLR.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -215,14 +215,16 @@ private static CancellationToken ExtractCancellationToken(Task task)
215215
try
216216
{
217217
task.GetAwaiter().GetResult();
218+
Debug.Fail("Waiting on the canceled task should always result in an OCE, even if it's manufactured at the time of the wait.");
219+
return new CancellationToken(true);
218220
}
219221
catch (OperationCanceledException oce)
220222
{
221-
CancellationToken ct = oce.CancellationToken;
222-
if (ct.IsCancellationRequested)
223-
return ct;
223+
// This token may not have cancellation requested; that's ok.
224+
// That can happen if, for example, the Task is canceled with
225+
// TaskCompletionSource<T>.SetCanceled(), without a token.
226+
return oce.CancellationToken;
224227
}
225-
return new CancellationToken(true);
226228
}
227229

228230
/// <summary>Dummy type to use as a void TResult.</summary>

src/System.Threading.Tasks/tests/UnwrapTests.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,10 @@ public static IEnumerable<object[]> CompletedNonGenericTasks
470470
yield return new object[] { Task.CompletedTask };
471471
yield return new object[] { Task.FromCanceled(CreateCanceledToken()) };
472472
yield return new object[] { Task.FromException(new FormatException()) };
473+
474+
var tcs = new TaskCompletionSource<int>();
475+
tcs.SetCanceled(); // cancel task without a token
476+
yield return new object[] { tcs.Task };
473477
}
474478
}
475479

@@ -481,6 +485,10 @@ public static IEnumerable<object[]> CompletedStringTasks
481485
yield return new object[] { Task.FromResult("Tasks") };
482486
yield return new object[] { Task.FromCanceled<string>(CreateCanceledToken()) };
483487
yield return new object[] { Task.FromException<string>(new FormatException()) };
488+
489+
var tcs = new TaskCompletionSource<string>();
490+
tcs.SetCanceled(); // cancel task without a token
491+
yield return new object[] { tcs.Task };
484492
}
485493
}
486494

0 commit comments

Comments
 (0)