2013-02-26 49 views
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被重新分配(即像一個方法,而不是一個屬性)。我錯過了什麼?

回答

3

感覺就像this.agent是越來越再分配每次我把它叫做 (即像個方法,而不是一個屬性)的時間。我錯過了什麼?

這正是發生了什麼,並在規範的文件(相關部分來自18.13.1如下)

靜態和實例屬性成員進行評估每次 成員被調用時。例如,在下文中, 構件的主體的每個C.Time評估時間來評價:

類型C()=

static member Time = System.DateTime.Now 

這是analgous您的情況

+0

衛生署!我今天跑在「愚蠢的」......謝謝。 – Akash 2013-02-26 11:27:50