Skip to content

Commit 0d70701

Browse files
committed
Reduce allocations
1 parent 140a26c commit 0d70701

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

src/FSharpPlus/Extensions/Task.fs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ module Task =
1919
elif t.IsCanceled then Canceled
2020
else invalidOp "Internal error: The task is not yet completed."
2121

22+
let inline private continueWith ([<InlineIfLambda>]f) (x: Task<'t>) =
23+
if x.IsCompleted then f x
24+
else x.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted (fun () -> f x)
25+
2226

2327
/// Creates a Task from a value
2428
let result (value: 'T) = Task.FromResult value
@@ -43,22 +47,25 @@ module Task =
4347
let private canceled<'T> : Task<'T> = Task.FromCanceled<'T> canceledTokenSingleton
4448

4549

46-
/// <summary>Creates a task workflow from 'source' another, mapping its result with 'f'.</summary>
50+
/// <summary>Creates a task workflow from 'source' workflow, mapping its result with 'mapper'.</summary>
51+
/// <param name="mapper">The mapping function.</param>
52+
/// <param name="source">The source task workflow.</param>
53+
/// <returns>The resulting task workflow.</returns>
4754
let map (mapper: 'T -> 'U) (source: Task<'T>) : Task<'U> =
4855
let source = nullArgCheck (nameof source) source
4956

5057
if source.IsCompleted then
5158
match source with
52-
| Succeeded r -> try result (mapper r) with e -> raise<'U> e
53-
| Faulted exn -> raise<'U> exn
54-
| Canceled -> canceled<'U>
59+
| Succeeded r -> try result (mapper r) with e -> raise e
60+
| Faulted exn -> raise exn
61+
| Canceled -> canceled
5562
else
5663
let tcs = TaskCompletionSource<'U> ()
5764
let k = function
58-
| Canceled -> tcs.SetCanceled ()
59-
| Faulted e -> tcs.SetException e.InnerExceptions
6065
| Succeeded r -> try tcs.SetResult (mapper r) with e -> tcs.SetException e
61-
source.ContinueWith k |> ignore
66+
| Faulted exn -> tcs.SetException exn.InnerExceptions
67+
| Canceled -> tcs.SetCanceled ()
68+
continueWith k source
6269
tcs.Task
6370

6471
/// <summary>Creates a task workflow from two workflows 'x' and 'y', mapping its results with 'f'.</summary>

0 commit comments

Comments
 (0)