Windows Polling Service Record

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() //Example open System.Threading let cts = new CancellationTokenSource() Async.Start(Async.poll 2000 (fun () -> printfn "%A" DateTime.Now), cts.Token) Thread.Sleep(TimeSpan.FromSeconds(10.0)) cts.Cancel() 

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.

+7
source share
1 answer

I may be tempted to write a simple loop in an asynchronous workflow. You can use do! Async.Sleep interval do! Async.Sleep interval for sleeping between polls - this has two advantages: you do not bind the thread, just to make it sit idle with Thread.Sleep , but do! automatically checks for cancellation for you if you pass a CancellationToken in Async.Start .

In addition, if your polling operation is connected to a network connection, you are already working with an asynchronous workflow, which makes making asynchronous network calls trivial.

+5
source

All Articles