有没有办法在 powershell foreach-object -parallel 中获取 TID(线程 ID)?

Is there a way to get the TID (thread id) in powershell foreach-object -parallel?

只是想知道我是否可以获得线程 ID 的 $TID,就像 $PID 或进程 ID,在 powershell 7 或 pwsh (https://github.com/PowerShell/PowerShell#-powershell). I can run this and see a bunch of threads with a TID column in sysinternals procexp (https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer) 中使用 foreach-object -parallel,在 pwsh.exe 属性,线程选项卡。

 1..20 | foreach-object -Parallel { start-sleep (5*$_) } -ThrottleLimit 20

进程 ID ($PID) 不同,no automatic PowerShell variable 反映了 thread ID(从 PowerShell 7.2 开始)。

如果获得 托管(相对于本机)线程 ID 就足够了,您可以使用 .NET API (System.Threading.Thread.CurrentThread):

1..2 | % -Parallel { [System.Threading.Thread]::CurrentThread.ManagedThreadId }

要获得本机线程ID,您需要平台特定解决方案通过P/Invoke;例如,对于 Windows,使用 GetCurrentThreadId() WinAPI 函数:

# For Windows
Add-Type -Name WinApi -Namespace demo -MemberDefinition @'
  [DllImport("Kernel32.dll")]
  public static extern uint GetCurrentThreadId();
'@

1..2 | % -Parallel { [demo.WinApi]::GetCurrentThreadId() }