我想实现的是让一个代理负责操作项目映射。这是一个容易的聚会,但现在我想知道如何在该地图上进行查询?
看看这段代码:
(* APPLIACATION STATE *)
let rec timeTable = Map.empty<string, TimeTableEntry>
let timeTableAgent = new TimeTableAgent(fun inbox ->
(* Internal functions *)
let validateCronExpr task =
try
task.CronExpr |> CrontabSchedule.Parse |> Success
with | ex -> Failure "Cron expression is invalid."
let rec schedule (timeTable : Map<string, TimeTableEntry>) (entry : TimeTableEntry) =
match validateCronExpr(entry) with
| Failure err -> Failure err
| Success _ -> match timeTable.ContainsKey(entry.Name) with
| false ->
let timeTable = timeTable.Add(entry.Name, entry)
Success "Task has been scheduled."
| true -> Failure "Task already exists."
(* message processing *)
let rec messageLoop (timeTable : Map<string, TimeTableEntry>) =
async {
let! message = inbox.Receive()
match message with
| Command.Schedule (entry, reply) ->
let timeTable = timeTable.Add(entry.Name, entry)
reply.Reply(schedule timeTable entry)
| Command.RecalculateOccurance (key, reply) -> reply.Reply(Success("OK"))
| Command.UnSchedule (key, reply) -> reply.Reply(Success("OK"))
return! messageLoop timeTable
}
// start the loop
messageLoop timeTable
)
timeTableAgent.Start()
let task = { Name = ""; CronExpr = "* * * * *"; Job = FileName(""); NextOccurance = DateTime.Now }
let messageAsync = timeTableAgent.PostAndAsyncReply(fun replyChannel -> Command.Schedule(task, replyChannel))
所以现在我想做这样的事情:
printf "%i" timeTable.Count
timeTable |> Map.iter (fun k v -> printf "%s" v.Name)
但项目计数为 0,查询不返回任何:(
我知道时间表的状态是不可变的,但我记得可以用新实例替换不可变的变量......
请问有人可以帮助我吗?
以上面的示例为例,您可以执行以下操作。
在代理消息处理程序中查找添加另一个命令
(** Previous match clauses **)
| Command.GetCount(reply) ->
reply.Reply(timeTable.Count)
然后,可以使用该命令查询代理状态的该视图
let timeTableCount = timeTableAgent.PostandReply(Command.GetCount)