1

Right now, I am attempting to manage boolean flags via a global hashtable:

# Context: System.IO.FileSystemWatcher
# File Event: 'Changed' 

$global:sourceId2Flag = @{}

...
$objectEventArgs = @{
  ...
  Action = {
    $nap = 1.0 / (Get-Random -Minimum 2 -Maximum 10)
    sleep $nap
    Write-Verbose $nap
    if ($global:sourceId2Flag[$event.MessageData.sourceId] -eq 0){
        $global:sourceId2Flag[$event.MessageData.sourceId]++
        Write-Verbose "Value was: $global:sourceId2Flag[$event.MessageData.sourceId]"
    }
  }
  ...
}
Register-ObjectEvent @objectEventArgs

And the main problem here is that I still generate ~3 (say, 2-6 events, depending on application that changes the file) events when the file is changed. It seems as if the hashtable is memcopied into the action context and so the gating does not work.

How would I properly set the hashtable flag so that other events do not get processed until I reset the hashtable flags to 0?


Alternatively, is there another way to solve this problem?

Chris
  • 28,822
  • 27
  • 83
  • 158
  • I am seeing some proliferation of the hash table state to events, but it is on the order of almost a minute...with no guarantees even as high as 20 seconds.. – Chris Sep 01 '23 at 16:00
  • is this hashtable being used from multiple action blocks? if so, this is not thread safe and might explain the issue – Santiago Squarzon Sep 01 '23 at 16:04
  • @SantiagoSquarzon the hash-table is used by many processes, but the keys are restricted to individual action blocks. – Chris Sep 01 '23 at 17:20
  • I'm not sure I understand the problem but, the first step I would take would be to change that hashtable for a `ConcurrentDictionary` the next step would be to use a locking mechanism on each `TValue` see here as an example: https://stackoverflow.com/a/75252238/15339544 – Santiago Squarzon Sep 02 '23 at 13:56

0 Answers0