我需要在 F# PCL 库中使用 System.Timers.Timer
。
我目前的目标是框架 4.5 并使用 Profile7(我使用了 VS 模板)并且它不允许访问 System.Timer。
根据 this SO answer,这是一个已知问题,已在 4.5.1 中解决。
我创建了一个 4.5.1 C# PCL 并检查了它的 .csproj。它针对框架 4.6 并使用 Profile32。
有没有办法在 F# 项目中定位相同的目标?我天真地尝试用 C# 值更新 .fsproj,但它破坏了一切。 :)
非常感谢!
最佳答案
System.Timers.Timer
(和 System.Threading.Timer
)类在主要的 F# PCL 配置文件中不起作用。鉴于支持普通 F# 异步,您可以通过编写自己的“计时器”类型轻松解决此问题。例如,以下(虽然有点难看)应该相当好地模仿 Timer
类功能:
type PclTimer(interval, callback) =
let mb = new MailboxProcessor<bool>(fun inbox ->
async {
let stop = ref false
while not !stop do
// Sleep for our interval time
do! Async.Sleep interval
// Timers raise on threadpool threads - mimic that behavior here
do! Async.SwitchToThreadPool()
callback()
// Check for our stop message
let! msg = inbox.TryReceive(1)
stop := defaultArg msg false
})
member __.Start() = mb.Start()
member __.Stop() = mb.Post true
关于f# - 我可以在 F# PCL 库中使用 System.Timers.Timer 吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29114973/