Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this equivalent to Task.Run?

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
like image 245
N_A Avatar asked Apr 11 '26 18:04

N_A


1 Answers

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}
like image 139
N_A Avatar answered Apr 13 '26 10:04

N_A