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

Commit ff0033b

Browse files
committed
Add fast path to Unwrap
When the outer task is already completed successfully, we can just return the inner task rather than manufacturing a new one and copying over the state.
1 parent 2616871 commit ff0033b

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ public static Task Unwrap(this Task<Task> task)
2929
{
3030
if (task == null)
3131
throw new ArgumentNullException("task");
32+
33+
// Fast path for an already successfully completed outer task: just return the inner one.
34+
// As in the subsequent slower path, a null inner task is special-cased to mean cancellation.
35+
if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0)
36+
{
37+
return task.Result ?? Task.FromCanceled(new CancellationToken(true));
38+
}
3239

3340
// Create a new Task to serve as a proxy for the actual inner task. Attach it
3441
// to the parent if the original was attached to the parent.
@@ -56,6 +63,13 @@ public static Task<TResult> Unwrap<TResult>(this Task<Task<TResult>> task)
5663
if (task == null)
5764
throw new ArgumentNullException("task");
5865

66+
// Fast path for an already successfully completed outer task: just return the inner one.
67+
// As in the subsequent slower path, a null inner task is special-cased to mean cancellation.
68+
if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0)
69+
{
70+
return task.Result ?? Task.FromCanceled<TResult>(new CancellationToken(true));
71+
}
72+
5973
// Create a new Task to serve as a proxy for the actual inner task. Attach it
6074
// to the parent if the original was attached to the parent.
6175
var tcs = new TaskCompletionSource<TResult>(task.CreationOptions & TaskCreationOptions.AttachedToParent);

0 commit comments

Comments
 (0)