f# - 如何在 F# Akka.NET Actor 中存储状态?

标签 f# actor akka.net

在 C# ReceiveActor s 我可以将状态作为类中的私有(private)字段。我应该如何使用 F# API 以惯用的方式执行此操作?

这是一个好主意吗?有什么选择吗?

let handleMessage (mailbox: Actor<'a>) msg =
    let mutable i = 1
    match msg with
    | Some x -> i <- i + x
    | None -> ()

最佳答案

您提出的方式完全适合作为在参与者中存储状态的一种方式。任何时候只处理 1 条消息的并发约束意味着不可能由于共享内存位置的争用而进入无效状态。

但是,这不是最惯用的选择。 Akka.Net 提供了一个 F# API 以与 F# MailboxProcessors 类似的方式与参与者一起工作。在这种情况下,您将您的 actor 定义为一个尾递归函数,该函数以一些新状态调用自身。这是一个例子

spawn system "hello" <|
    fun mailbox ->
        let rec loop state =
            actor {
                let! msg = mailbox.Receive ()
                printfn "Received %A. Now received %s messages" msg state
                return! loop (state + 1) //Increment a counter for the number of times the actor has received a message
            }
        loop 0

有关 Akka.Net F# API 的完整文档,请参阅 http://getakka.net/wiki/FSharp%20API

关于f# - 如何在 F# Akka.NET Actor 中存储状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29100748/

相关文章:

c# - Akka.Net 远程处理 : ActorSelection vs. IActorRef

visual-studio - Visual Studio 2010 智能感知 : hints on F# operators

f# - 编译错误提示值不是函数

c++ - 游戏 Actor 脚本

f# - 具有状态 monad 的代理(异步)

scala - 使用 Netty 和 Scala Actor 的异步 http 请求

f# - 如何使用 Akka.FSharp API 在 Akka.NET 集群中实现故障转移?

parsing - 为什么我的递归 FParsec 解析器在解析嵌套数组时会抛出异常?

泛型:类型应该对另一种类型进行操作,而是对声明的文字值进行操作?

.net-core - 使用 .NET Core 进行 net46 框架的 AKKA.NET 配置