title: Limit the number of parallel threads in C#
body: <p>I am writing a C# program to generate and upload a half million files via FTP. I want to process 4 files in parallel since the machine have 4 cores and the file generating takes much longer time. Is it possible to convert the following Powershell example to C#? Or is there any better framework such as Actor framework in C# (like F# MailboxProcessor)?</p>
  
  <p><strong><a href="http://blogs.msdn.com/b/powershell/archive/2011/04/04/scaling-and-queuing-powershell-background-jobs.aspx" rel="noreferrer">Powershell example</a></strong></p>
  
  <pre><code>$maxConcurrentJobs = 3;
  
  # Read the input and queue it up
  $jobInput = get-content .\input.txt
  $queue = [System.Collections.Queue]::Synchronized( (New-Object System.Collections.Queue) )
  foreach($item in $jobInput)
  {
      $queue.Enqueue($item)
  }
  
  # Function that pops input off the queue and starts a job with it
  function RunJobFromQueue
  {
      if( $queue.Count -gt 0)
      {
          $j = Start-Job -ScriptBlock {param($x); Get-WinEvent -LogName $x} -ArgumentList $queue.Dequeue()
          Register-ObjectEvent -InputObject $j -EventName StateChanged -Action { RunJobFromQueue; Unregister-Event $eventsubscriber.SourceIdentifier; Remove-Job $eventsubscriber.SourceIdentifier } | Out-Null
      }
  }
  
  # Start up to the max number of concurrent jobs
  # Each job will take care of running the rest
  for( $i = 0; $i -lt $maxConcurrentJobs; $i++ )
  {
      RunJobFromQueue
  }
  </code></pre>
  
  <p><strong>Update:</strong><br>
  The connection to remote FTP server can be slow so I want to limit the FTP uploading processing. </p>