Skip to content

Instantly share code, notes, and snippets.

@AlbertoDePena
Last active May 27, 2021 14:41
Show Gist options
  • Save AlbertoDePena/2cf6655edb627062cf72fd99ed78e46e to your computer and use it in GitHub Desktop.
Save AlbertoDePena/2cf6655edb627062cf72fd99ed78e46e to your computer and use it in GitHub Desktop.
[<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