我有一个f# 3.0代理包装在一个类中:
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: %dn"
f.Send () |> printf "Reply: %dn"
f.Send () |> printf "Reply: %dn"
我得到了预期的响应:
Reply: 1
Reply: 2
Reply: 3
但是,如果我删除代理的let绑定并直接将其分配给this。代理房地产:
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时代理都被重新初始化。感觉是这样的。每次我调用它时,agent都被重新分配(即像方法一样,而不是属性)。我错过了什么?
感觉是这样的。每次我打电话,探员都会被重新分配(即像一个方法,而不是一个属性)。我错过了什么?
这就是所发生的事情,并且在规范中有文档记录(下面是18.13.1的相关部分)
静态和实例属性成员在每次成员被调用。例如,在下面的代码中,c .计算时间:
类型C () =static member Time = System.DateTime.Now
这与你的情况类似