Running many child processes in parallel

Part of my program creates a bunch of child processes and has them run in the background, roughly as follows
class Runner : IDisposable {
  ConcurrentBag<Process> Processes = []
  ...
  void Execute() {
    ...
    Parallel.ForEach(items, item => {
      string Command = ...
      Processes.Add(Process.Start(Command));
    }
  }
  ...
  void Dispose() {
    foreach (var p in Processes) {
      // ?
    }
  }
}

I want to know
  • What's the proper way to dispose currently running processes in case it's needed (can I simply try p.Kill() followed by p.Dispose()?)
  • Is there a way to limit the number of threads spawned by foreach in this scenario?
Was this page helpful?