title: How to limit the number of processes being spawned at a time?
body: <p>I am working on a VB.NET Windows Forms application where the user is supposed to be able to determine how many processes the application is allowed to launch at a time.</p>
  
  <p>My current method mostly works but I've noticed that occasionally the application goes over the set amount. I use two global variables for this, <code>_ConcurrentRuns</code> which is 0 at the start of the application, and <code>_MaxConcurrentRuns</code> which is set by the user.</p>
  
  <pre class="lang-vb prettyprint-override"><code>Private _sync As new Object()
  
  ' This is called Synchronously
  Private Function RunModel() As Boolean
      If CancelExectuion Then Return CancelCleanup()
  
      Do While True
          SyncLock _sync
              If _ConcurrentRuns &lt; _MaxConcurrentRuns Then
                  Interlocked.Increment(_ConcurrentRuns)
                  Exit Do
              End If
          End SyncLock
          Threading.Thread.Sleep(50)
      Loop
  
      'This is what will launch an individual process and close it when finished
      ret = RunApplication(arg)
      ' The process has been closed so we decrement the concurrent runs
      Interlocked.Decrement(_ConcurrentRuns)
  
      Return ret
  End Function
  </code></pre>
  
  <p>The goal is to let only one thread exit the while loop at a time, I'm not able to catch it in the debug mode however in the task manager it will occasionally go 1-3 processes over what it's supposed to use. This makes me assume that somehow multiple threads are getting inside the synclock somehow, but I have no clue how that could be happening. </p>
  
  <p>I will be very grateful for any and all help that can be provided, thanks for taking the time to read my question.</p>