[英]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. 我有一个要在async
上下文中使用的阻塞调用blockingFoo()
。 I would like to run it on another thread, so as to not block the async
. 我想在另一个线程上运行它,以免阻塞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. Async.StartAsTask
随后是Async.AwaitTask
有效地互相抵消,其副作用是在进程中创建的Task
实际上触发了对线程池中包含blockingFoo
的异步块的评估。 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. 如果要从另一个异步块中触发对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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.