我正在尝试在 PowerShell 中创建一个简单的去抖动函数。这是我到目前为止所拥有的。
# timer.ps1
# Define debounce function
Function New-Debounce {
param(
[scriptblock]$ScriptBlock,
[int]$DelayMilliseconds
)
$timer = $null
$id = $null
return {
# reset timer
if ($timer) {
$timer.Stop()
$timer.Dispose()
}
$timer = [System.Timers.Timer]::new($DelayMilliseconds)
# only fire once
$timer.AutoReset = $false
$timer.Start()
# Listen for the Elapsed event and execute our script block when it occurs
$id = Register-ObjectEvent `
-InputObject $timer `
-EventName "Elapsed" `
-SourceIdentifier "Timer.Debounce" `
-Action { Write-Host "Hello!"; & $ScriptBlock }
}.GetNewClosure()
}
$f = New-Debounce -ScriptBlock { Write-Host "There" } -DelayMilliseconds 1000
& $f
# # Keep the process alive so the timer can do its thing
for ($i = 0; $i -lt 5; $i++) {
Start-Sleep -Seconds 1
}
Unregister-Event "Timer.Debounce"
运行timer.ps1总是输出“Hello”,但从不输出“There”,我不确定为什么。
为什么当计时器触发时我传递的 $ScriptBlock 不会被执行?您将如何改进这段代码?
-MessageData
将 $ScriptBlock
传递到操作块:
# Listen for the Elapsed event and execute our script block when it occurs
$registerObjectEventSplat = @{
InputObject = $timer
EventName = 'Elapsed'
SourceIdentifier = 'Timer.Debounce'
MessageData = $ScriptBlock
Action = { Write-Host 'Hello!'; & $event.MessageData }
}
$id = Register-ObjectEvent @registerObjectEventSplat