asynchronous - 这等同于 Task.Run 吗?

标签 asynchronous f# task

我正在编写一个 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/

相关文章:

javascript - Node 中 API 调用的 header

c# - 多个客户端的异步 TCP 服务器

f# - 在 F# 中查找最大值、最小值和平均值

.net - F# 中的函数应用运算符 ($)?

c# - 如何区分Task Scheduler 1.0和Task Scheduler 2.0?

c++ - 如何在 C++ 中执行跨平台异步文件 I/O

c++ - Googletest:如何异步运行测试?

exception - 如何在带有 goto 或类似语言的解释器中实现 Try/Except/Finally?

c# - List<Task> - 使用 C# Entity Framework 的 UPSERT 数据库记录

JavaFX:控制台登录 TextArea + 多线程和任务