简体   繁体   中英

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

I have a blocking call blockingFoo() that I would like to use in an async context. I would like to run it on another thread, so as to not block the async .

Here is my solution:

let asyncFoo = 
  async {
    blockingFoo() |> ignore
  }
  |> Async.StartAsTask
  |> Async.AwaitTask
  • Is this the correct way to do this?

  • Will this work as expected?

I think you're a bit lost. Async.StartAsTask followed by Async.AwaitTask effectively cancel each other, with the side-effect that the Task created in the process actually triggers evaluation of the async block containing blockingFoo on the thread pool. So it works, but in a way that betrays expectations.

If you want to trigger evaluation of asyncFoo from within another async block, a more natural way to do it would be to use Async.Start if you don't want to await its completion, or Async.StartChild if you do.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM