Skip to content

Commit e8d19f9

Browse files
committed
Fix
1 parent c6200cb commit e8d19f9

File tree

1 file changed

+18
-29
lines changed

1 file changed

+18
-29
lines changed

src/FSharpPlus/Extensions/Task.fs

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,32 +20,26 @@ module Task =
2020
else invalidOp "Internal error: The task is not yet completed."
2121

2222
/// <summary>Creates a task workflow from 'source' another, mapping its result with 'f'.</summary>
23-
let map (f: 'T -> 'U) (source: Task<'T>) : Task<'U> =
23+
let map (mapper: 'T -> 'U) (source: Task<'T>) : Task<'U> =
2424
let source = nullArgCheck (nameof source) source
2525

26-
if source.Status = TaskStatus.RanToCompletion then
27-
try Task.FromResult (f source.Result)
28-
with e ->
29-
let tcs = TaskCompletionSource<'U> ()
30-
tcs.SetException e
31-
tcs.Task
26+
if source.IsCompleted then
27+
match source with
28+
| Succeeded r ->
29+
try Task.FromResult (mapper r)
30+
with e -> Task.FromException<'U> e
31+
| Faulted exn -> Task.FromException<'U> exn
32+
| Canceled -> Task.FromCanceled<'U> (CancellationToken true)
3233
else
3334
let tcs = TaskCompletionSource<'U> ()
34-
if source.Status = TaskStatus.Faulted then
35-
tcs.SetException (Unchecked.nonNull source.Exception).InnerExceptions
36-
tcs.Task
37-
elif source.Status = TaskStatus.Canceled then
38-
tcs.SetCanceled ()
39-
tcs.Task
40-
else
41-
let k = function
42-
| Canceled -> tcs.SetCanceled ()
43-
| Faulted e -> tcs.SetException e.InnerExceptions
44-
| Succeeded r ->
45-
try tcs.SetResult (f r)
46-
with e -> tcs.SetException e
47-
source.ContinueWith k |> ignore
48-
tcs.Task
35+
let k = function
36+
| Canceled -> tcs.SetCanceled ()
37+
| Faulted e -> tcs.SetException e.InnerExceptions
38+
| Succeeded r ->
39+
try tcs.SetResult (mapper r)
40+
with e -> tcs.SetException e
41+
source.ContinueWith k |> ignore
42+
tcs.Task
4943

5044
/// <summary>Creates a task workflow from two workflows 'x' and 'y', mapping its results with 'f'.</summary>
5145
/// <remarks>Workflows are run in sequence.</remarks>
@@ -408,13 +402,8 @@ module Task =
408402
ran <- true
409403
try
410404
let task = body ()
411-
let rec loop (task: Task<'T>) (compensation : unit -> unit) =
412-
match task.Status with
413-
| TaskStatus.RanToCompletion -> compensation (); task
414-
| TaskStatus.Faulted -> task.ContinueWith((fun (x:Task<'T>) -> compensation (); x)).Unwrap ()
415-
| TaskStatus.Canceled -> task
416-
| _ -> task.ContinueWith((fun (x:Task<'T>) -> (loop x compensation: Task<_>))).Unwrap ()
417-
loop task compensation
405+
if task.IsCompleted then compensation (); task
406+
else task.ContinueWith(fun (_: Task<'T>) -> compensation (); task).Unwrap ()
418407
with _ ->
419408
compensation ()
420409
reraise ()

0 commit comments

Comments
 (0)