sdgfsdh
sdgfsdh

Reputation: 37121

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

Upvotes: 3

Views: 317

Answers (1)

scrwtp
scrwtp

Reputation: 13577

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
}

Upvotes: 7

Related Questions