0

I'm just trying to start and kill multiple instances of the same program with different arguments. Starting is not a problem but how can I kill a process with a specific argument?

static void Start(string args)
{
    var process = new Process
    {
        StartInfo = { FileName = "FileName", Arguments = args }
    };
    process.Start();
}

This is my method to start procs with args.

I tried to reserve it somehow, but I wasn't successful. I already searched on Google for the last hour, but didn't get any helpful results.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Mendax M.
  • 5
  • 1
  • 6
  • Use a Dictionary to store the processes. – SinOfficial Jun 29 '19 at 20:42
  • A dictionary will work, but if this dictionary lives/exists for a longer time, don't forget to dispose the Process objects from the dictionary if they are not useful anymore. Otherwise, your program might hold onto/leak process handles through the dictionary holding onto Process objects. (See also here: https://stackoverflow.com/questions/16957320/what-does-process-dispose-actually-do) –  Jun 29 '19 at 20:48

1 Answers1

0

Use a Dictionary<string, Process> to store the processes and args:

static Dictionary<string, Process> processes = new Dictionary<string, Process>();

static void StartProcess(string args)
{
    var process = new Process
    {
        StartInfo = { FileName = "FileName", Arguments = args }
    };
    process.Start();
    processes.Add(args, process);
}

static void StopProcess(string args)
{
    var process = processes[args];
    process.Kill();
    process.Dispose();
    processes.Remove(args);
}
SinOfficial
  • 536
  • 5
  • 15