Files
winutil/functions/public/Invoke-WPFRunspace.ps1
T
Chris TitusandGitHub 93dc23dd66 Speed up runspace and tab initialization (#4793)
* Add startup performance tracing

* Lazy initialize non-default tabs

* Render install app entries incrementally

* Defer and cache toggle status checks

* Clean up runspace invocation ownership

* Defer GUI runspace pool startup

* Defer status taskbar asset rendering

* Record final speed verification

* Fix deferred install render timer callback

* Add dispatcher smoke coverage for install rendering

* Replace install render timer with dispatcher callbacks

* Gate performance tracing behind compile switch

* Clean up analyzer warnings in speed changes

* Speed up runspace and tab initialization
2026-07-01 23:34:59 -05:00

97 lines
2.6 KiB
PowerShell

function Invoke-WPFRunspace {
<#
.SYNOPSIS
Creates and invokes a runspace using the given scriptblock and argumentlist
.PARAMETER ScriptBlock
The scriptblock to invoke in the runspace
.PARAMETER ArgumentList
A list of arguments to pass to the runspace
.PARAMETER ParameterList
A list of named parameters that should be provided.
.EXAMPLE
Invoke-WPFRunspace `
-ScriptBlock $sync.ScriptsInstallPrograms `
-ArgumentList "Installadvancedip,Installbitwarden" `
Invoke-WPFRunspace`
-ScriptBlock $sync.ScriptsInstallPrograms `
-ParameterList @(("PackagesToInstall", @("Installadvancedip,Installbitwarden")),("ChocoPreference", $true))
#>
[CmdletBinding()]
Param (
$ScriptBlock,
$ArgumentList,
$ParameterList
)
if (-not ("WinUtilRunspaceCleanup" -as [type])) {
Add-Type @"
using System;
using System.Management.Automation;
public sealed class WinUtilRunspaceCleanupState
{
public PowerShell PowerShell { get; set; }
public IAsyncResult Handle { get; set; }
}
public static class WinUtilRunspaceCleanup
{
public static void Cleanup(object state, bool timedOut)
{
var cleanupState = state as WinUtilRunspaceCleanupState;
if (cleanupState == null || cleanupState.PowerShell == null || cleanupState.Handle == null)
{
return;
}
try
{
cleanupState.PowerShell.EndInvoke(cleanupState.Handle);
}
catch
{
}
finally
{
cleanupState.PowerShell.Dispose();
}
}
}
"@
}
Initialize-WinUtilRunspacePool | Out-Null
# Create a PowerShell instance
$powershell = [powershell]::Create()
# Add Scriptblock and Arguments to runspace
[void]$powershell.AddScript($ScriptBlock)
[void]$powershell.AddArgument($ArgumentList)
foreach ($parameter in $ParameterList) {
[void]$powershell.AddParameter($parameter[0], $parameter[1])
}
$powershell.RunspacePool = $sync.runspace
# Execute the RunspacePool
$handle = $powershell.BeginInvoke()
$cleanupState = [WinUtilRunspaceCleanupState]::new()
$cleanupState.PowerShell = $powershell
$cleanupState.Handle = $handle
$cleanupCallback = [System.Threading.WaitOrTimerCallback][WinUtilRunspaceCleanup]::Cleanup
[System.Threading.ThreadPool]::RegisterWaitForSingleObject($handle.AsyncWaitHandle, $cleanupCallback, $cleanupState, -1, $true) | Out-Null
# Return the handle
return $handle
}