2
我有一個F#3.0劑包裹在一個類:F#奇怪劑重新初始化行爲
type AgentWrapper() =
let myAgent = Agent.Start(fun inbox ->
let rec loop (state: int) =
async {
let! (replyChannel: AsyncReplyChannel<int>) = inbox.Receive()
let newState = state + 1
replyChannel.Reply newState
return! loop newState
}
loop 0)
member private this.agent = myAgent
member this.Send() =
this.agent.PostAndReply (fun replyChannel -> replyChannel)
當我將消息發送到它,如下所示:
let f = new AgentWrapper()
f.Send() |> printf "Reply: %d\n"
f.Send() |> printf "Reply: %d\n"
f.Send() |> printf "Reply: %d\n"
我得到預期的迴應:
Reply: 1
Reply: 2
Reply: 3
但是,如果我刪除讓綁定的劑並將其直接分配給this.agent屬性:
type AgentWrapper() =
member private this.agent = Agent.Start(fun inbox ->
let rec loop (state: int) =
async {
let! (replyChannel: AsyncReplyChannel<int>) = inbox.Receive()
let newState = state + 1
replyChannel.Reply newState
return! loop newState
}
loop 0)
member this.Send() =
this.agent.PostAndReply (fun replyChannel -> replyChannel)
然後我得到的答覆:
Reply: 1
Reply: 1
Reply: 1
我已經在這盯着幾個小時,我不明白爲什麼代理我每次打電話給AgentWrapper.Send都會重新初始化。每次我打電話時,感覺就像this.agent被重新分配(即像一個方法,而不是一個屬性)。我錯過了什麼?
衛生署!我今天跑在「愚蠢的」......謝謝。 – Akash 2013-02-26 11:27:50