I'm writing an F# application and I want to get rid of explicit references to task as much as possible. Is the following equivalent to Task.Run
or am I missing something?
[<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}
Example usage (untested):
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