title: Powershell synchronized hash table thread safety
body: <p>I have a WPF script running into problems recently.</p>
  <p>The script does subnet scanning using PSParallel module. When the subnet CIDR is less than 21, it starts having the problem.</p>
  <p>The problem is:
  I have a concurrent queue as a member of a synchronized hash table. The queue is used for producer/consumer model. The scanning threads keep enqueue the data and the GUI thread keep dequeue data and write it to a richtextbox. The dequeue process is handled by a dispatch timer event handler, which is executed every 20 ms. When the CIDR &gt;=21, there is no problem. But when CIDR &lt;21, sometimes it will throw an error message:</p>
  <pre class="lang-none prettyprint-override"><code>Collection was modified; enumeration operation may not execute.
  At E:\PSScanner\PSScanner.ps1:446 char:8
  +     if($syncHash.Q.Count -ne 0){
  +        ~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : OperationStopped: (:) [], InvalidOperationException
      + FullyQualifiedErrorId : System.InvalidOperationException
  </code></pre>
  <p>I think the synchronized hash table is thread safe and the concurrent queue is thread safe as well. Not sure why is this happening.</p>
  <p>The source code is here:
  <a href="https://github.com/MeCRO-DEV/PSScanner" rel="nofollow noreferrer">https://github.com/MeCRO-DEV/PSScanner</a></p>