V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
AndyAO
V2EX  ›  问与答

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

  •  2
     
  •   AndyAO · 2021-09-09 08:01:16 +08:00 · 685 次点击
    这是一个创建于 931 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

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

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

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

    第 1 条附言  ·  2021-09-09 09:36:18 +08:00
    geelaw 的答案很完美的解决了该问题,Thanks♪(・ω・)ノ
    1 条回复    2021-09-09 08:32:15 +08:00
    geelaw
        1
    geelaw  
       2021-09-09 08:32:15 +08:00   ❤️ 1
    这是因为你混淆了两种处理 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 同一个事件回立刻返回,如果想要等下一次发生,需要删除后重新添加。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1481 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 17:22 · PVG 01:22 · LAX 10:22 · JFK 13:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.