我有一个阻塞调用blockingFoo()
,我想在async
上下文中使用它。我想在另一个线程上运行它,这样就不会阻塞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
}