Skip to content

Commit a300076

Browse files
committed
Use task approach
1 parent d1eb920 commit a300076

File tree

1 file changed

+14
-29
lines changed

1 file changed

+14
-29
lines changed

src/FSharpPlus/Extensions/ValueTask.fs

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -243,22 +243,20 @@ module ValueTask =
243243

244244
/// Flattens two nested ValueTask into one.
245245
let join (source: ValueTask<ValueTask<'T>>) : ValueTask<'T> =
246-
let tcs = TaskCompletionSource<'T> ()
247-
continueTask tcs source (fun x ->
248-
continueTask tcs x (fun x ->
249-
tcs.SetResult x))
250-
tcs.Task |> ValueTask<'T>
246+
if source.IsCompleted then
247+
match source with
248+
| Succeeded inner -> inner
249+
| Faulted aex -> raise aex
250+
| Canceled -> canceled
251+
else
252+
let tcs = TaskCompletionSource<'T> ()
253+
continueTask tcs source (fun inner ->
254+
continueTask tcs inner tcs.SetResult)
255+
ValueTask<'T> tcs.Task
251256

252257

253258
/// <summary>Creates a ValueTask workflow from 'source' workflow, mapping and flattening its result with 'f'.</summary>
254-
let bind (f: 'T -> ValueTask<'U>) (source: ValueTask<'T>) : ValueTask<'U> =
255-
let tcs = TaskCompletionSource<'U> ()
256-
continueTask tcs source (fun x ->
257-
try
258-
continueTask tcs (f x) (fun fx ->
259-
tcs.SetResult fx)
260-
with e -> tcs.SetException e)
261-
tcs.Task |> ValueTask<'U>
259+
let bind (f: 'T -> ValueTask<'U>) (source: ValueTask<'T>) : ValueTask<'U> = source |> Unchecked.nonNull |> map f |> join
262260

263261
/// <summary>Creates a ValueTask that ignores the result of the source ValueTask.</summary>
264262
/// <remarks>It can be used to convert non-generic ValueTask to unit ValueTask.</remarks>
@@ -319,23 +317,10 @@ module ValueTask =
319317
compensation ()
320318
try
321319
let task = body ()
322-
if task.IsCompleted then
323-
try
324-
compensation ()
325-
task
326-
with e -> raise e
320+
if task.IsCompleted then compensation (); task
327321
else
328-
let tcs = TaskCompletionSource<'T> ()
329-
let f = function
330-
| Succeeded r -> tcs.SetResult r
331-
| Faulted aex -> tcs.SetException aex.InnerExceptions
332-
| Canceled -> tcs.SetCanceled ()
333-
task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted (fun () ->
334-
try
335-
compensation ()
336-
f task
337-
with e -> tcs.SetException e)
338-
ValueTask<'T> tcs.Task
322+
let t = task.AsTask()
323+
t.ContinueWith(fun (_: Task<'T>) -> compensation (); t).Unwrap () |> ValueTask<'T>
339324
with _ ->
340325
compensation ()
341326
reraise ()

0 commit comments

Comments
 (0)