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
As @Daniel pointed out, this is better achieved using Async.StartChild like this:
[<AutoOpen>]
module Async =
let inline runInThreadPool backgroundTask = async {
let! result = backgroundTask() |> Async.StartChild
return! result}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With