Last active
May 27, 2021 14:41
-
-
Save AlbertoDePena/2cf6655edb627062cf72fd99ed78e46e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[<RequireQualifiedAccess>] | |
module Async = | |
open System | |
open System.Threading | |
open System.Threading.Tasks | |
let singleton x = async { | |
return x | |
} | |
let map f (computation: Async<'t>) = async { | |
let! x = computation | |
return f x | |
} | |
let bind f (computation: Async<'t>) = async { | |
let! x = computation | |
return! f x | |
} | |
let AsTask (task : Async<unit>) = Async.StartAsTask task :> Task | |
/// <summary> | |
/// Runs the asynchronous computation in a loop until 'Ctrl+C' is pressed. | |
/// </summary> | |
/// <param name="milliseconds">The number of milliseconds to sleep between each asynchronous computation execution.</param> | |
/// <param name="computation">The asynchronous computation.</param> | |
let RunUntilCancelled (milliseconds: int) computation = | |
let looper = async { | |
while (not <| Async.DefaultCancellationToken.IsCancellationRequested) do | |
do! computation | |
do! Async.Sleep milliseconds | |
} | |
try | |
use cancellationSource = new CancellationTokenSource() | |
let callback _ (args : ConsoleCancelEventArgs) = | |
args.Cancel <- true | |
cancellationSource.Cancel() | |
let handler = ConsoleCancelEventHandler(callback) | |
Console.CancelKeyPress.AddHandler handler | |
Async.RunSynchronously (looper, cancellationToken = cancellationSource.Token) | |
with | |
| :? OperationCanceledException -> () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment