I am running some code in a while loop to ensure a program is always running. If the program isn’t running it starts it, if the program isn’t there it copies it from a backup and then starts it, nothing fancy:
while (true)
{
Process backup = new Process();
ProcessStartInfo check = new ProcessStartInfo(file);
if (Process.GetProcessesByName(file).Length == 0)
{
if(File.Exists(file))
{
backup.StartInfo = check;
backup.Start();
}
else if (!File.Exists(file))
{
File.Copy(backupFile, file);
Thread.Sleep(250);
backup.StartInfo = check;
backup.Start();
}
}
backup.Close();
Thread.Sleep(2000);
}
The problem is after each cycle the ram usage goes up by about 100KB which isn’t a lot I know but if this is running for an hour or so it’s going to cause big problems.
I have tried pausing it and using .Close() on the process but no joy. Any ideas are much appreciated.
Put these lines inside the if statement so they are not executed unless the process is not running:
Since
ProcessimplementsIDisposable, you can wrap it in a using statement, as Oded suggested.You do not have an actual memory leak. When the garbage collector runs, the memory will be reclaimed. If the temporary memory usage is a problem, you could force the GC to run, but I think once you do #1 you will not have a problem with the temporary memory usage either.