Skip to content

Instantly share code, notes, and snippets.

@eulerfx
Last active June 27, 2018 14:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save eulerfx/c731c900db3471f493bcce04cf6d9a0f to your computer and use it in GitHub Desktop.
F# Async Cache
let cache (a:Async<'a>) : Async<'a> =
let tcs = TaskCompletionSource<'a>()
let state = ref 0
async {
if (Interlocked.CompareExchange(state, 1, 0) = 0) then
Async.StartWithContinuations(
a,
tcs.SetResult,
tcs.SetException,
(fun _ -> tcs.SetCanceled()))
return! tcs.Task |> Async.AwaitTask }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment