难题:为什么 PowerShell 的 Wait-Event 在事件触发后仍没有反应?

2021-09-09 08:01:16 +08:00
 AndyAO

注册 Windows 的点击通知的事件后,弹出通知,并立即调用 Wait-Event 。

当事件已经被触发后,等待仍未结束。

这到底是什么原因导致的?

查看了很多相关 Cmdlet 的文档,找不到原因,难道是我忽略了什么重要的事情吗?

在这里可以看到整个脚本:gist.github.com/e9b2949165fae074d3ad6651b762b848

(脚本的参数都有默认值,可以直接运行)

693 次点击
所在节点    问与答
1 条回复
geelaw
2021-09-09 08:32:15 +08:00
这是因为你混淆了两种处理 object event 的方式,如果你 Register-ObjectEvent 的时候传入了 Action,那么 Wait-Event 的效果是未定义,因为文档 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/wait-event

This feature provides an alternative to polling for an event. It also allows you to determine the response to an event in two different ways:

- using the Action parameter of the event subscription
- waiting for an event to return and then respond with an action

第一项的意思是 Register-XyzEvent 的时候传入 Action 参数,第二项的意思是可以 Wait-Event 一个(没有传入 Action )的 event source identifier 。

如果你想既有超时,又可以处理 event,可以这样做:

# 不要传入 Action
Register-ObjectEvent $balloon BalloonTipClicked -sourceIdentifier $SourceIdentifier
$balloon.ShowBalloonTip(5000)
$event = Wait-Event -timeout -1 -sourceIdentifier $SourceIdentifier
if ($event -eq $null)
{
Write-Host "超时"
}
else
{
Write-Host "没有超时"
& $OnClicked
}

另外 Wait-Event 成功一次后再 Wait-Event 同一个事件回立刻返回,如果想要等下一次发生,需要删除后重新添加。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/800733

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX