Action-based object events sometimes lost Action-based object events sometimes lost powershell powershell

Action-based object events sometimes lost


You are "losing" events because you end your script too early. Your event action defined by Register-ObjectEvent ([Utils.StaticEventTest]) Fired -SourceIdentifier $srcId -Action { $global:recvd++ } will be executed asynchronously to your script. If I repeat what you did, I get even worse results (maybe due to a virtual environment):

C:\Users\user\Desktop>for /l %n in (1, 1, 10) do @powershell.exe  -executionPolicy remoteSigned -file test.ps1total 1000 events fired - 17 receivedtotal 1000 events fired - 100 receivedtotal 1000 events fired - 202 receivedtotal 1000 events fired - 16 receivedtotal 1000 events fired - 3 receivedtotal 1000 events fired - 120 receivedtotal 1000 events fired - 1 receivedtotal 1000 events fired - 162 receivedtotal 1000 events fired - 1 receivedtotal 1000 events fired - 27 received

But when I add a Start-Sleep -Seconds 5 after your for-loop, I get this result (at least in my environment):

C:\Users\user\Desktop>for /l %n in (1, 1, 10) do @powershell.exe  -executionPolicy remoteSigned -file test.ps1total 1000 eventstotal 1000 eventstotal 1000 eventstotal 1000 eventstotal 1000 eventstotal 1000 eventstotal 1000 eventstotal 1000 eventstotal 1000 eventstotal 1000 events

So all events you fired are there, no event is lost. But if you want to see the action taken on them right after you fired them, you have to wait until all (asynchronous) actions have been performed.

Of course, Start-Sleep with a fixed time span is not an option here, because you cannot know how long it takes for a system to execute all actions. But it shows the reason, why you think you are losing events.

A possible way to wait for your events would be this line after your for-loop:

while ($global:recvd -lt $fired) {Start-Sleep -Milliseconds 10}

This even works for 100.000 events per iteration (really tried):

C:\Users\user\Desktop>for /l %n in (1, 1, 10) do @powershell.exe  -executionPolicy remoteSigned -file test.ps1total 100000 eventstotal 100000 eventstotal 100000 eventstotal 100000 eventstotal 100000 eventstotal 100000 eventstotal 100000 eventstotal 100000 eventstotal 100000 eventstotal 100000 events

Not a single event lost. This makes me believe that the firing and listening for events works as expected. I am not able to reproduce any counterproof.