我正在编写一个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
答案 0 :(得分:1)
正如@Daniel指出的那样,使用Async.StartChild
更好地实现这一点:
[<AutoOpen>]
module Async =
let inline runInThreadPool backgroundTask = async {
let! result = backgroundTask() |> Async.StartChild
return! result}