AndyAO
V2EX  ›  问与答

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

  •  2
     
  •   AndyAO · Sep 9, 2021 · 1122 views
    This topic created in 1747 days ago, the information mentioned may be changed or developed.

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

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

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

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

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

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

    Supplement 1  ·  Sep 9, 2021
    geelaw 的答案很完美的解决了该问题,Thanks♪(・ω・)ノ
    1 replies    2021-09-09 08:32:15 +08:00
    geelaw
        1
    geelaw  
       Sep 9, 2021   ❤️ 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 同一个事件回立刻返回,如果想要等下一次发生,需要删除后重新添加。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2882 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 15:07 · PVG 23:07 · LAX 08:07 · JFK 11:07
    ♥ Do have faith in what you're doing.