Why Does TaskList.exe Never End When Redirecting Standard Output?

396 views Asked by At

When I attempt to run tasklist.exe with the Process class and set RedirectStandardOutput to true, the process never ends.

using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        RunProcess("tasklist.exe");
    }

    private static void RunProcess(string command)
    {
        var process = new Process()
        {
            StartInfo =
            {
                FileName = command,
                RedirectStandardOutput = true,
                UseShellExecute = false
            }
        };

        process.Start();
        process.WaitForExit();
    }
}

If I set RedirectStandardOutput to false, the process does end!!!

Why does the tasklist.exe Process never end? I am using Windows 7 and .net framework 4.5.2.

I found out that when I forcefully close tasklist.exe, there is exactly 4096 bytes written to standard output every time! Is there some kind of character buffer that I need to increase in size?

1

There are 1 answers

2
Mário Moura da Silva On BEST ANSWER

If you're using RedirectStandardOutput = true add this line to your code:

process.Start();

// To avoid deadlocks, always read the output stream first and then wait.
string out = process.StandardOutput.ReadToEnd();

process.WaitForExit();