powershell - 自定义睡眠功能可在不挂起时使 UI 睡眠 - 问题:计时器略微漂移
问题描述
我编写了一个自定义Start-SleepNoUIHang
函数来休眠 Windows 窗体 UI,同时不挂起它以允许使用ForEach
循环进行用户交互,并在该循环内调用它[System.Windows.Forms.Application]::DoEvents()
以防止它这样做。
它按我的意图工作,但唯一的问题是函数稍微偏离了参数$Milliseconds
。
如果我将其设置为说5000
计时器大约需要6300
几毫秒。
我试图在ForEach
循环中添加一个计数器,然后在它到达$Milliseconds
参数时退出它,但这似乎不起作用。
我不想使用 .net 计时器,所以我将它创建为单行,以便在程序中需要它的任何地方使用。
在这里的任何帮助将不胜感激。
这是代码(带注释):
<#
This function attempts to pause the UI without hanging it without the need for a
timer event that does work.
The only trouble is that the timer slight drifts more than the provided
$Milliseconds argument.
#>
function Start-SleepNoUIHang {
Param
(
[Parameter(Mandatory = $false, HelpMessage = 'The time to wait in milliseconds.')]
[int]$Milliseconds
)
$timeBetween = 50 # This value seems to be a good value in order for the UI not to hang itself.
$timeElapsed = 0 # Increment this to check and break out of the ForEach loop.
# ($Milliseconds/$timeBetween)*$timeBetween # Time is the total wait time in milliseconds.
1..($Milliseconds/$timeBetween) | ForEach {
Start-Sleep -Milliseconds $timeBetween
Try { [System.Windows.Forms.Application]::DoEvents() } catch{} # A try catch here in case there's no windows form.
$timeElapsed = $timeElapsed + $timeBetween # Increment the $timeElapsed counter.
Write-Host $timeElapsed
# This doesn't seem to have any effect on the timer. It ends on its own accord.
if ($timeElapsed -gt $Milliseconds) {
Write-Host 'Break'
break
}
}
}
$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
Write-Host "Started at $(get-date)"
Start-SleepNoUIHang -Milliseconds 5000
Write-Host "Ended at $(get-date)"
Write-Host "Total Elapsed Time: $($elapsed.Elapsed.ToString())"
我也尝试过用这个替换 ForEach 循环的 While 循环,但行为相同。
While ( $Milliseconds -gt $timeElapsed ) {
$timeElapsed = $timeElapsed + $timeBetween # Increment the $timeElapsed counter.
Start-Sleep -Milliseconds $timeBetween
Write-Host $timeElapsed
}
解决方案
推荐阅读
- php - Wordpress:如何通过 REST API 使用 Wordpress 帖子格式
- python - 在kivyMD的MDToolbar中更改图标的颜色?
- symfony - Symfony 5 / Mercure > 私人更新。获取 CORS
- javascript - 为什么在这里创建一个新数组而不是清空旧数组会导致问题?
- ssl - Mosquitto websockets ERR_CONNECTION_REFUSED letencrypt
- php - Laravel 迁移“连接被拒绝”[2002] | 数据库正确 | 全新安装
- c# - 如何在不同的脚本中影响 bool
- swiftui - 观察 SwiftUI 中的帧变化
- javascript - JavaScript 将隐藏数据添加到 Object
- c# - SQLite 获取 int 而不是 float