【发布时间】:2011-09-24 05:10:36
【问题描述】:
我通常使用 C# 编写 Windows 服务,但我尝试使用 F#。对于像这样的轮询服务,我通常使用自己编写的类,类似于BackgroundWorker。它产生一个后台线程并定期触发一个 OnWork 方法。 (完整代码为here [github]。)
在 F# 中是否有另一种可能更好或更惯用的方法来做到这一点?这可能是编写轮询后台工作者类或内置替代方案的更好方法。
编辑
这是我根据 Joel 的建议提出的。
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()
服务使用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)
我希望有一种方法可以避免可变的CancellationTokenSource,但是唉。
【问题讨论】:
-
在相关说明中,有人创建了 F# 服务模板。它可能包含一些好的样板代码,但它不包含任何关于轮询的内容。 visualstudiogallery.msdn.microsoft.com/…
-
我看到了。谢谢。我希望我知道如何发布对它的一些改进建议。
-
+1 用您的解决方案更新您的问题。
标签: f# windows-services backgroundworker