I usually write Windows services in C #, but I give it a switch to F #. For a poll like this, I usually use a class that I wrote that looks like BackgroundWorker . It generates a background thread and periodically runs the OnWork method. (The full code is here [github] .)
Is there any other, possibly better or more idiomatic way to do this in F #? This may be the best way to write a background class for polling, or built-in alternatives to it.
EDIT
This is what I raised based on Joelโs assumption.
module Async = open System.Diagnostics let poll interval work = let sw = Stopwatch() let rec loop() = async { sw.Restart() work() sw.Stop() let elapsed = int sw.ElapsedMilliseconds if elapsed < interval then do! Async.Sleep(interval - elapsed) return! loop() } loop()
Service using poll :
type MyService() = inherit System.ServiceProcess.ServiceBase() let mutable cts = new CancellationTokenSource() let interval = 2000 override __.OnStart(_) = let polling = Async.poll interval (fun () -> //do work ) Async.Start(polling, cts.Token) override __.OnStop() = cts.Cancel() cts.Dispose() cts <- new CancellationTokenSource() override __.Dispose(disposing) = if disposing then cts.Dispose() base.Dispose(true)
I'm sorry that there was no way to avoid the modified CancellationTokenSource , but alas.
Daniel
source share