F#在另一个线程上运行阻塞调用,在异步工作流中使用

sdg*_*sdh 2 f# asynchronous

我有一个blockingFoo()要在async上下文中使用的阻止呼叫。我想在另一个线程上运行它,以免阻塞async

这是我的解决方案:

let asyncFoo = 
  async {
    blockingFoo() |> ignore
  }
  |> Async.StartAsTask
  |> Async.AwaitTask
Run Code Online (Sandbox Code Playgroud)
  • 这是正确的方法吗?

  • 会按预期工作吗?

scr*_*wtp 5

我觉得你有点迷路了。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
}
Run Code Online (Sandbox Code Playgroud)