Micha
Micha

Reputation: 69

C# process management

We are trying to implement a program which starts processes. But simultaneously there can be maximum up to 2 processes running in memory. If the number of processes is more than 2 we get exception because of licensing policies. So basically we need to wait until 2 processes end and then start another 2 until we're done. I tried to check if in memory there are 2 or more processes then make thread sleep but it does not seem to work fine

while (Process.GetProcesses().Where(x => x.ProcessName == "myProcessName").Count() >= 2)
{
 Thread.Sleep(100);
}
//Start next process

Any ideas? Thanks a lot!

Upvotes: 0

Views: 3197

Answers (4)

Micha
Micha

Reputation: 69

We have found temporary solution:

while (true)
  {
    lock (_lock)
    {
      if (Process.GetProcesses().Where(x => x.ProcessName == "processName").Count() < GetProcessNumber)
      {
        //do Smth
        break;
      }
      Thread.Sleep(1000);
    }
  }

Upvotes: 0

hippibruder
hippibruder

Reputation: 168

This would consider already running processes and also only start new processes, if the previously running processes all exited.

string processName = "calc";
int processCount = 2;

while ( true )
  {
  while ( Process.GetProcessesByName( processName ).Count() < processCount )
    {
    Process.Start( processName );
    }

  var tasks = from p in Process.GetProcessesByName( processName )
              select Task.Factory.StartNew( p.WaitForExit );
  Task.WaitAll( tasks.ToArray() ); 
  }

Upvotes: 0

Deathspike
Deathspike

Reputation: 8800

You can start the processes and wait for the Exited event to re-start another like so:

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
    class Program {
        static void StartProcess(string Path) {
            Process Process = Process.Start(Path);
            Process.EnableRaisingEvents = true;
            Process.Exited += (sender, e) => {
                StartProcess(Path);
            };
        }

        static void Main(string[] args) {
            for (int i = 0; i < 2; i++) {
                StartProcess("notepad");
            }
            Console.ReadLine();
        }
    }
}

Upvotes: 2

TalentTuner
TalentTuner

Reputation: 17556

Seems like you need SemaPhore to ensure that atmax 2 process running at a time

Upvotes: 2

Related Questions