如何在F#Akka.NET Actor中存储状态? [英] How to store state in an F# Akka.NET Actor?

查看:79
本文介绍了如何在F#Akka.NET Actor中存储状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C# ReceiveActors I can just have state as private fields in the class. How should I do this in an idiomatic way with the F# API?

这是个好主意吗?

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


推荐答案

您提出的方法完全合适作为在演员内部存储状态的一种手段。任何时候仅处理1条消息的并发性约束意味着,由于在共享内存位置上的争用,不可能进入无效状态。

The way you've proposed is entirely appropriate as a means of storing the state within the actor. The concurrency constraints of only processing 1 message at any time means that it's not possible to get into invalid states as a result of contention on a shared memory location.

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

However, it's not the most idiomatic option. Akka.Net provides an F# API to work with actors in a similar way to F# MailboxProcessors. In this case you define your actor as a tail recursive function which calls itself with some new state. Here's an example

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

For full documentation on the Akka.Net F# API see http://getakka.net/wiki/FSharp%20API

这篇关于如何在F#Akka.NET Actor中存储状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆