如何终止在PowerShell脚本中停止的线程

时间:2015-03-04 09:20:56

标签: multithreading powershell

我有以下代码来刻录所有核心上的所有CPU:

<#
.SYNOPSIS
Script similar to BurnCpu Chaos Monkey

.DESCRIPTION
Using the largest int32 positive integer, this script calculates the factorial to generate 100% CPU utilisation.
The script fills all CPUs.

Source ForEach-Parallel: https://powertoe.wordpress.com/2012/05/03/foreach-parallel/
Source maxin out CPU of single core: https://dthomo.wordpress.com/2012/04/19/use-powershell-to-max-out-cpu-usage/

.EXAMPLE
Chaos-BurnCPU

#>.

function ForEach-Parallel {
    param(
        [Parameter(Mandatory=$true,position=0)]
        [System.Management.Automation.ScriptBlock] $ScriptBlock,
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [PSObject]$InputObject,
        [Parameter(Mandatory=$false)]
        [int]$MaxThreads=5
    )
    BEGIN {
        $iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
        $pool = [Runspacefactory]::CreateRunspacePool(1, $maxthreads, $iss, $host)
        $pool.open()
        $threads = @()
        $ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param(`$_)`r`n" + $Scriptblock.ToString())
    }
    PROCESS {
        $powershell = [powershell]::Create().addscript($scriptblock).addargument($InputObject)
        $powershell.runspacepool=$pool
        $threads+= @{
            instance = $powershell
            handle = $powershell.begininvoke()
        }
    }
    END {
        $notdone = $true
        while ($notdone) {
            $notdone = $false
            for ($i=0; $i -lt $threads.count; $i++) {
                $thread = $threads[$i]
                if ($thread) {
                    if ($thread.handle.iscompleted) {
                        $thread.instance.endinvoke($thread.handle)
                        $thread.instance.dispose()
                        $threads[$i] = $null
                    }
                    else {
                        $notdone = $true
                    }
                }
            }
        }
    }
}

# Burn CPU of all cores.
$numberOfCores = (Get-WmiObject -Class win32_processor).NumberOfCores
(0..$numberOfCores) | ForEach-Parallel -MaxThreads $numberOfCores {
    foreach ($number in 1..2147483647) { 
        $result = $result * $number 
    }
}

不幸的是,当脚本停止时,进程会继续运行并保持100%的CPU,直到我们终止进程。我们怎样才能实现END在ForEach-Parallel函数中运行或以其他方式完成线程的清理?

1 个答案:

答案 0 :(得分:2)

这里使用运行空间的方法略有不同:

Invoke-ScriptAsynch

这允许您在运行空间上指定超时。它还允许您在powershell实例的输出流中保留信息。您可以让脚本将其进程ID($ PID)写入详细或调试流,并使用该脚本来杀死进程。