今天我在 MailboxProcessor 的迭代中实现一些简单处理时遇到了问题。
起初我尝试使用 Seq.map 进行迭代,但从未调用过迭代中的代码!然后我改用 Seq.iter 进行迭代,然后处理就完成了……
type Agent<'Msg> = MailboxProcessor<'Msg>
...
let agent =
Agent.Start((fun agent ->
let rec loop =
async {
let! msg = agent.Receive()
match msg with
| SensorEvent(id, ts) ->
...
[for x in connections.[id] -> x]
|> Seq.map (fun light_id -> //Seq.iter works just fine here, Seq.map doesn't!
let publish = new Publish<SimulatorBroker.SimLightOffMsg>()
publish.Message <- new SimulatorBroker.SimLightOffMsg(light_id, recom_ts)
peer.Publish(box publish :?> IPublish<_>)
)
|> ignore
return! loop
}
loop), tokenSource.Token)
我感到困惑的是为什么我不能使用 Seq.map?...现在我想知道当它没有分配给任何东西时它是否会被优化?或者当你使用 Seq 时是否会发生其他奇怪的事情。在邮箱处理器中映射..?
是的,我知道 Seq.iter 更适合无论如何只返回“单位”的简单迭代。但请原谅我,我还在学习;)。