Reputation: 37121
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?
Upvotes: 3
Views: 317
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