C# Program automation - Program hangs/doesn't work

171 views Asked by At

I've been trying to make a program to automate the process of running different processes on my computer. So far I've got the following program running a console version of BleachBit(It's like CCleaner), the process appears in task manager, it hits around 25kb process RAM then CPU usage goes to 0% and just sits there doing nothing for ages and never quits.

Is there something wrong I'm doing in my code that could cause this to happen? I've tried editing the app.manifest to make sure the program has to be run as admin in case it needed more privileges

Also when running similar code in a bat file to run the program, it's opens its own windows and runs fine, so I'm not sure. Any help in the right direction would be fantastic.

The code I'm running is below.

static void Main(string[] args)
    {
        string Log = "";
        if (File.Exists(Environment.CurrentDirectory + "\\BleachBit\\bleachbit_console.exe"))
        {
            Log += "File exists";
            Log += RunProgramCapturingOutput("\\BleachBit\\bleachbit_console.exe", "--preset --clean");
        }
        else
            Log += "Program not found. Please place at \\BleachBit\\bleachbit_console.exe";
        File.WriteAllText("log.txt", Log);
        Console.ReadLine();
    }

    public static string RunProgramCapturingOutput(string filename, string arguments)
    {
        ProcessStartInfo processInfo = new ProcessStartInfo()
        {
            FileName = Environment.CurrentDirectory + filename,
            Arguments = arguments,
            CreateNoWindow = false,
            UseShellExecute = false,
            WorkingDirectory = Path.GetDirectoryName(Environment.CurrentDirectory + filename),
            RedirectStandardError = false,
            RedirectStandardOutput = true
        };

        Process process = Process.Start(processInfo);
        process.WaitForExit();

        string output = output = process.StandardOutput.ReadToEnd();
        Console.WriteLine("Output: " + output);

        process.Close();
        return output;
    }
1

There are 1 answers

0
Joshua On BEST ANSWER

Switching these lines to this:

string output = output = process.StandardOutput.ReadToEnd(); process.WaitForExit();

allows to avoid deadlocks. The program seems to be a relatively slow running program due to hard-drive I/O, just give it time and you'll see it complete.

I found this deadlock issue from https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput(v=vs.110).aspx

Where it states in a code block: "// To avoid deadlocks, always read the output stream first and then wait."