簡體   English   中英

F#在另一個線程上運行阻塞調用,在異步工作流中使用

[英]F# run blocking call on another thread, use in async workflow

我有一個要在async上下文中使用的阻塞調用blockingFoo() 我想在另一個線程上運行它,以免阻塞async

這是我的解決方案:

let asyncFoo = 
  async {
    blockingFoo() |> ignore
  }
  |> Async.StartAsTask
  |> Async.AwaitTask
  • 這是正確的方法嗎?

  • 會按預期工作嗎?

我覺得你有點迷路了。 Async.StartAsTask隨后是Async.AwaitTask有效地互相抵消,其副作用是在進程中創建的Task實際上觸發了對線程池中包含blockingFoo的異步塊的評估。 因此,它起作用了,但是卻超出了期望。

如果要從另一個異步塊中觸發對asyncFoo評估,一種更自然的方法是使用Async.Start如果您不想等待其完成),或者使用Async.StartChild

let asyncFoo = 
    async {
        blockingFoo() |> ignore
    }

async {
    // "fire and forget"
    asyncFoo |> Async.Start

    // trigger the computation
    let! comp = Async.StartChild asyncFoo

    // do other work here while comp is executing

    // await the results of comp
    do! comp
}

暫無
暫無

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

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