我正在编写一个 F# 应用程序,我想尽可能地摆脱对任务的显式引用。以下是否等同于 Task.Run
还是我遗漏了什么?
[<AutoOpen>]
module Async =
let inline runInThreadPool backgroundTask = async {
let originalContext = System.Threading.SynchronizationContext.Current
do! Async.SwitchToThreadPool()
let! result = backgroundTask()
do! Async.SwitchToContext originalContext
return result}
示例用法(未经测试):
async { // starts on the UI thread
let! result = Async.runInThreadPool(fun _ -> async {
let mutable sum= 0
for i in 1..10000 do
sum <- sum + 1
return sum })
//do something with the result in the UI
} |> Async.StartImmediate
最佳答案
正如@Daniel 指出的那样,使用 Async.StartChild
可以更好地实现这一点:
[<AutoOpen>]
module Async =
let inline runInThreadPool backgroundTask = async {
let! result = backgroundTask() |> Async.StartChild
return! result}
关于asynchronous - 这等同于 Task.Run 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24247074/