[英]F# run blocking call on another thread, use in async workflow
我有一個要在async
上下文中使用的阻塞調用blockingFoo()
。 我想在另一個線程上運行它,以免阻塞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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.