簡體   English   中英

使用F#的異步函數中沒有輸出?

[英]No output in asynchronous functions using F#?

嘗試使用Blocking Queue和此處給出的代碼來實現讀寫器問題。 整個過程都已編譯並運行,但是reader()和writer()函數中async {...}中的部分均未產生任何輸出。 我敢肯定他們會被正確調用,因為即使我是F#的菜鳥,帶有此代碼的教程頁面似乎也是真實的。

這是整個代碼:

open System
open System.IO
open System.Collections.Generic
//open System.Runtime.Serialization.Formatters.Binary

///defining Agent
type Agent<'T> = MailboxProcessor<'T>

///defining Message
type internal BlockingAgentMessage<'T> = 
  | Get of AsyncReplyChannel<'T>
  | Add of 'T * AsyncReplyChannel<unit> 

/// Agent-based implementation of producer/consumer problem 
type BlockingQueueAgent<'T>(maxLength) =
    let agent = Agent.Start(fun agent ->
        let queue = new Queue<_>()
        //let queue = new Queue()
        // State machine running inside the agent
        let rec emptyQueue() = 
            agent.Scan(fun msg ->
                match msg with 
                | Add(value, reply) -> Some(enqueueAndContinue(value, reply))
                | _ -> None )
        and fullQueue() = 
            agent.Scan(fun msg ->
                match msg with 
                | Get(reply) -> Some(dequeueAndContinue(reply))
                | _ -> None )
        and runningQueue() = async {
            let! msg = agent.Receive() 
            match msg with 
            | Add(value, reply) -> return! enqueueAndContinue(value, reply)
            | Get(reply) -> return! dequeueAndContinue(reply) }
        and enqueueAndContinue (value, reply) = async {
            queue.Enqueue(value)
            reply.Reply() 
            return! chooseState() }
        and dequeueAndContinue (reply) = async { 
            reply.Reply(queue.Dequeue())
            return! chooseState() }
        and chooseState() = 
            if queue.Count = 0 then emptyQueue()
            elif queue.Count = maxLength then fullQueue()
            else runningQueue()

        // Start with an empty queue
        emptyQueue() )

    /// Asynchronously adds item to the queue. If the queue
    /// is full, it blocks until some items are removed.
    member x.AsyncAdd(v:'T) = 
        agent.PostAndAsyncReply(fun ch -> Add(v, ch))

    /// Asynchronously gets item from the queue. If the queue
    /// is empty, it blocks until some items are added.
    member x.AsyncGet() = 
        agent.PostAndAsyncReply(Get)




let ag = new BlockingQueueAgent<int>(3)
printfn "Blocking Queue Agent program"

let writer() = async {

    for i in 0 .. 10 do 
        do! ag.AsyncAdd(i)
        printfn "Added: %d" i }

let reader () = async { 
    while true do
        let! v = ag.AsyncGet()
        do! Async.Sleep(1000)
        printfn "Got: %d" v }

reader () |> Async.Start
printfn "Started Reader ..."
writer () |> Async.Start
printfn "Started Writer ..."

代碼很好- async執行之前,您的程序剛剛退出。 只需添加類似

System.Console.Read() |> ignore

到最后。 這對我有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM