multithreading - 为什么我在使用 Async.Parallel 时只有一个线程 id?

标签 multithreading asynchronous f#

为什么我在使用 Async.Parallel 时只有一个处理器 ID?

代码:

open System
open System.Threading

[for i in 1..10 -> async {return i}] |> Async.Parallel
                                     |> Async.RunSynchronously
                                     |> Seq.iter (fun i -> printfn "Processor Id: %d Value: %d" Thread.CurrentThread.ManagedThreadId i)

输出:

Processor Id: 1 Value: 1
Processor Id: 1 Value: 2
Processor Id: 1 Value: 3
Processor Id: 1 Value: 4
Processor Id: 1 Value: 5
Processor Id: 1 Value: 6
Processor Id: 1 Value: 7
Processor Id: 1 Value: 8
Processor Id: 1 Value: 9
Processor Id: 1 Value: 10
val it : unit = ()

> 

最佳答案

您正在从您的主线程执行 printfn,在您的异步工作流程之外。试试这个:

[for i in 1..10 -> 
    async {return sprintf "Processor Id: %d Value: %d" Thread.CurrentThread.ManagedThreadId i}] 
|> Async.Parallel
|> Async.RunSynchronously

关于multithreading - 为什么我在使用 Async.Parallel 时只有一个线程 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509149/

相关文章:

c - epoll:添加到 epoll-fd 的 SD 与事件上的实际 SD 值不同

c# - 使用 WPF MVVM Light DispatcherHelper

dictionary - 如何通过 F# 中的键将两个 map 相交

c++ - 发出信号并保持 pthread 打开的有效方法?

java - ScheduledThreadPoolExecutor.remove : Is it safe to use

asynchronous - 是否可以使用 CaSTLe.DynamicProxy 创建异步拦截器?

javascript - 回调返回未定义

javascript - 设置 bcrypt 以与 Passport 和 async-await Node.js 库配合使用

f# - 如何像 REPL 一样从 F# 打印

charts - 为什么这个 XPlot.Plotly 代码不能编译>