-
Notifications
You must be signed in to change notification settings - Fork 22
Add Async.withCancellation #685
Copy link
Copy link
Open
Description
Add Async.withCancellation
I propose we add Async.withCancellation. This would allow using outside CancellationToken, such as the RequestAborted from HttpContext. The problem with Async.Start is it does not provide a way to return a value.
The existing way of approaching this problem in F# is provided here:
https://gist.github.com/eulerfx/c41d50c6fba8e88cf16a21ed7c3c14bd#file-async-withcancellation-fs
Inlined:
let withCancellation (ct:CancellationToken) (a:Async<'a>) : Async<'a> = async {
let! ct2 = Async.CancellationToken
use cts = CancellationTokenSource.CreateLinkedTokenSource (ct, ct2)
let tcs = new TaskCompletionSource<'a>()
use _reg = cts.Token.Register (fun () -> tcs.TrySetCanceled() |> ignore)
let a = async {
try
let! a = a
tcs.TrySetResult a |> ignore
with ex ->
tcs.TrySetException ex |> ignore }
Async.Start (a, cts.Token)
return! tcs.Task |> Async.AwaitTask }
Pros and Cons
The advantages of making this adjustment to F# are
- This would be easily discoverable to more user
- Potentially implemented in a cleaner way
The disadvantages of making this adjustment to F# are
- None I know of
Extra information
Estimated cost (XS, S, M, L, XL, XXL): XS
Related suggestions: (put links to related suggestions here)
Affidavit (please submit!)
Please tick this by placing a cross in the box:
- This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
- I have searched both open and closed suggestions on this site and believe this is not a duplicate
- This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.
Please tick all that apply:
- This is not a breaking change to the F# language design
- I or my company would be willing to help implement and/or test this
Reactions are currently unavailable