Click here to Skip to main content
Click here to Skip to main content

Launching a process and displaying its standard output

, 31 Aug 2003 CPOL
Rate this:
Please Sign up or sign in to vote.
This article shows how to launch a process (such as a bat file, perl script, console program) and have its standard output displayed on a windows form.

Sample Image - LaunchProcess.png

Introduction

I wanted to launch a script from a Windows Form application and display the standard output in a text box as the process was running.  Surely you're not surprised to learn that multithreading is involved.  It turns out you'll have at least four threads running to do this simple task.  To keep things simple and sane, I've reused code from other another source, so I must first give credit to the MSDN article "Give Your .NET-based Application a Fast and Responsive UI with Multiple Threads"  by I.D. Griffiths.  I highly suggest reading this article for more background on multithreading in Windows Forms applications.  Thanks also to Chad Christensen for his suggestions in using a RichTextBox.

Creating a class to call a process

A script or executable can be run using System.Diagnostics.Process.  The string FileName is set to the executable (e.g. perl.exe, Run.bat, ConsoleApplication.exe).  The string Arguments is set to the command-line arguments for that executable (e.g. perlscript.pl, filename1.txt filename2.txt, etc).  The following code will start that executable.

    Process process = new Process();
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.FileName = FileName;
    process.StartInfo.Arguments = Arguments;
    process.StartInfo.WorkingDirectory = WorkingDirectory;
    process.Start();

Notice that the standard output and standard error have both been redirected.  There are two StreamReaders in the Process class that can be used to read the output: Process.StandardOutput and Process.StandardError.  Often, the output is not read until after the process has finished, as in the following:

    string output = process.StandardOutput.ReadToEnd();

Reading to the end will not work for this application, since we want to read the data as the process is running.

Multiple threads

The solution is to use multiple threads.  One thread is dedicated to running the process and two more threads are dedicated to reading the standard error and standard output.  This is mentioned in MSDN documentation.  Each of these two threads will run a simple function that sits in a loop reading from the stream until the stream is closed.

    void ReadStdOut()
    {
        string str;
        while ((str = process.StandardOutput.ReadLine()) != null)
        {
            // do something with str
        }
    }

After each line is read into str, we would like to notify a windows form to display the text.  Raising an event is probably the best way to accomplish this.  For every new line of text received (on either StandardOutput or StandardError) an event will be raised.  A windows form class can subscribe to these events and update a text box.  Simple, but it won't quite work without some additional work.

Important rule of windows forms

There is an important rule of windows forms and multithreading.  Controls are (almost entirely) not thread safe.  This means that an event raised from any thread other than the UI Thread cannot use methods or properties of a control.  There are a few methods guaranteed to be safe including Control.Invoke and Control.BeginInvoke.  These methods are used to run a function on the UI thread. 

Thankfully, we can inherit from the class AsyncOperation (written by I.D. Griffiths from the above mentioned MSDN article) to solve several problems.  First, this class allows us to raise an event on a UI thread of a hosting or target control.  The above function becomes:

    public delegate void DataReceivedHandler(object sender,
        DataReceivedEventArgs e);

    public event DataReceivedHandler StdOutReceived;

    void ReadStdOut()
    {
        string str;
        while ((str = process.StandardOutput.ReadLine()) != null)
        {
            FireAsync(StdOutReceived, this, new DataReceivedEventArgs(str));
        }
    }

FireAsync is a method provided by the class AsyncOperation.  It raises an event (or more specifically invokes any delegate) on the UI thread of a form or control.  StdOutReceived is the event that will be raised.  DataReceivedEventArgs is a class derived from EventArgs that has a single string containing the text to be displayed (its definition is not shown here for brevity).

The second thing AsyncOperation provides is a method of canceling a process.  Let's take a look at that class in more detail.

Inheriting from AsyncOperation

AsyncOperation is an abstract base class that assists in creating cancelable worker threads that can fire events back on a UI control (or form).  It provides two main methods that are called by a form class: Start() and Cancel().

AsyncOperation requires that one method be overridden: DoWork(). This method is called when the Start() method is called.  As the method runs, it is expected to watch for a flag CancelRequested that is set from a call to Cancel().  If the flag is true, the method should acknowledge the cancel and return.

The implementation of DoWork() is as follows:

    void protected override void DoWork()()
    {
        // Start a new process for the cmd
        Process process = new Process();
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.FileName = FileName;
        process.StartInfo.Arguments = Arguments;
        process.StartInfo.WorkingDirectory = WorkingDirectory;
        process.Start();

        
        // Invoke stdOut and stdErr readers - each
        // has its own thread to guarantee that they aren't
        // blocked by, or cause a block to, the actual
        // process running (or the gui).
        new MethodInvoker(ReadStdOut).BeginInvoke(null, null);
        new MethodInvoker(ReadStdErr).BeginInvoke(null, null);

        // Wait for the process to end, or cancel it
        while (! process.HasExited)
        {
            Thread.Sleep(SleepTime); // sleep
            if (CancelRequested)
            {
                // Not a very nice way to end a process,
                // but effective.
                process.Kill();
                AcknowledgeCancel();
            }
        }

    }

The methods DoWork()ReadStdOut(), and ReadStdErr(), the properties FileName and Arguments, and the events StdOutReceived and StdErrReceived are all added to a class ProcessCaller which derives from AsyncOperation.  Both classes can be downloaded as part of the zipfile at the top of the page.

The form

As shown in the picture above, the form is quite simple.  It consists of a rich text box to show the standard output and standard input, a button to run a process (Ok), and a button to cancel the process (Cancel).

The Ok button calls the Start() method on ProcessCaller and the Cancel button calls the Cancel() method.  The events StdOutRecieved and StdErrReceived are handled by the following function:

    private void writeStreamInfo(object sender, DataReceivedEventArgs e)
    {
        this.richTextBox1.AppendText(e.Text + Environment.NewLine);
    }

Improvements

Adding a progress bar to the form is one nice improvement for the user interface.  Of course, you have to know the progress of the program being run.  One option is to have the script tell you explicitly in the standard output with lines such as: "Percent completion = 30".  Your "writeStreamInfo" function would filter those lines and update a progress bar.

Standard Error can be displayed in red or some other color (or in a separate rich text box) to highlight any errors found.  At the end of the process, a dialog could be displayed with a list of all errors.

Providing support for standard input shouldn't be too difficult, but integrating it with the windows form may be tough.  Perhaps a separate single-line text box whose contents are sent to the standard input stream through a method on ProcessCaller.

These are just a few ideas of improvements you can make.

Conclusion

Using the class AsyncOperation reduced the design complexity of this program.  Hopefully, the class ProcessCaller will provide you just as much help in reducing the complexity of running scripts and monitoring the output.

Revision History

  • 2003-Jul-31 : Original Post
  • 2003-Aug-05 : Fixed some spelling / grammatical mistakes (oops)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mike Mayer

United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberactualmanx19-Feb-14 4:31 
QuestionFails to catch exceptions from start process Pinmembergrafne7919-Aug-11 0:25 
GeneralDisconnectedContext was detected Errror PinmemberJason Hubbard28-Aug-09 15:48 
GeneralWant to do same in Web forms Pinmembert_bala1822-Jun-09 15:48 
GeneralCaptureConsole.DLL - A Universal Console Output Redirector for all Compilers PinmemberElmue18-Jun-09 13:57 
QuestionSuspending and resuming the process Pinmemberohad-oz21-Nov-08 6:59 
QuestionUsing "redirectstandardinput" with this Pinmemberimmortaldeath19-Sep-08 8:47 
GeneralA bit of a newb here, but figured I would give it a try. Pinmemberimmortaldeath3-Sep-08 18:58 
GeneralAbout the article "Launching a process and displaying the standard output" on Code project PinmemberAnupama Sankaran28-Aug-08 8:58 
QuestionTerminate process on standard error Pinmemberoidele27-Oct-07 10:19 
QuestionGUI blocked PinmemberMeJVZ6-Jul-07 8:17 
GeneralYour code does not work always VERY STRANGE PinmemberElmue14-Dec-06 22:08 
GeneralRe: I found the reason PinmemberElmue15-Dec-06 4:32 
GeneralRe: I found the reason PinmemberRYU^^1-Mar-07 18:10 
GeneralRe: I found the reason Pinmembercggiriraj17-Mar-08 4:00 
GeneralRe: I found the reason Pinmemberzeiksz18-Jun-09 0:34 
QuestionVS2005 update? Pinmembertaumuon25-Jul-06 7:11 
AnswerRe: VS2005 update? PinmemberPushkar Pathak22-Aug-06 15:55 
GeneralAnother way... PinmemberAlun Evans25-Jul-06 3:37 
Questionstdin solution??? Pinmembersilvepaadmin9-Jun-06 18:13 
GeneralSource code not working with VS 2005 Pinmemberjelewis8-Jun-06 6:29 
AnswerRe: Source code not working with VS 2005 PinmemberClaudia aus Hannover7-Aug-06 21:44 
Generalqueuing jobs Pinmemberbillou_2_k7-Mar-06 8:05 
GeneralMessage order PinmemberSerialHobbyist17-Feb-06 23:17 
GeneralA question about Multi-files' print by Process Pinmemberlovvver20-Jan-06 21:13 
GeneralStart process to display output PinmemberZuoping2-Aug-05 9:58 
GeneralRe: Start process to display output Pinmemberlovvver8-Feb-06 16:37 
General[Message Deleted] PinmemberRoboRubik27-Jul-05 9:19 
GeneralRe: Does not require multiple threads Pinmemberiohn200024-Oct-05 9:28 
GeneralStandard Input - Binary data PinmemberHanika25-Jul-05 10:29 
I have been struggling with this for a few days now. I am hoping someone has some ideas!
 
I am running a C program (EXE) using the process class. The program inputs and outputs binary data. I have code that works for files under 60 KB but StandardInput gets stuck at some point for larger files. Here is my code:
 
Dim pInfo As New ProcessStartInfo
Dim timeOut As Integer = 5000
Dim Ascii As Encoding = Encoding.Default
 
With pInfo
.FileName = FormFontRoot & "bin\findpage.exe"
.Arguments = PageNum.ToString & " " & PageNum.ToString
.WindowStyle = ProcessWindowStyle.Hidden
.CreateNoWindow = True
.UseShellExecute = False
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
End With
 
'Start the process.
Dim p As Process = Process.Start(pInfo)
 
'Write to standard Input
Dim br As BinaryReader = New BinaryReader(File.Open(FileName,FileMode.Open))
Dim Bytes(4096) As Byte
Dim BytesRead As Integer
Dim totalBytes As Integer = 0
While br.PeekChar <> -1
BytesRead = br.Read(Bytes, 0, Bytes.Length)
totalBytes = totalBytes + BytesRead
 
p.StandardInput.BaseStream.Write(Bytes, 0, BytesRead) '--> stuck here
end while
br.Close()
p.StandardInput.Close()
 
''Write to stdOUt
Dim FileOut As String = FileName & ".p" & PageNum.ToString
If IO.File.Exists(FileOut) Then IO.File.Delete(FileOut)
 
Dim FileStrm As FileStream = New FileStream(FileOut, _
FileMode.CreateNew, FileAccess.Write, FileShare.Write)
 
Dim bw As BinaryWriter = New BinaryWriter(FileStrm)
BytesRead = p.StandardOutput.BaseStream.Read(Bytes, 0, Bytes.Length)
While BytesRead <> 0
bw.Write(Bytes, 0, BytesRead)
BytesRead = p.StandardOutput.BaseStream.Read(Bytes, 0,Bytes.Length)
End While
bw.Close()
p.StandardOutput.Close()
 
p.WaitForExit(timeOut)
 

GeneralXCopy bat file with .NET BETA PinmemberMitch Rivera12-Jul-05 7:49 
GeneralMultiple arguments to a new process Pinmembertazfan14-Apr-05 6:37 
GeneralRe: Multiple arguments to a new process PinmemberRoboRubik27-Jul-05 7:52 
GeneralProblem with .bat PinsussAnonymous8-Apr-05 23:15 
Generalffmpeg PinmemberCyberTech7-Apr-05 9:38 
GeneralRe: ffmpeg PinmemberRaviprakash R21-Dec-07 6:52 
GeneralRe: ffmpeg Pinmembertingspain16-Feb-09 15:35 
Generalchkdsk PinmemberJim S.9-Feb-05 2:33 
GeneralRe: chkdsk PinmemberDQM6-Mar-06 15:49 
GeneralRe: chkdsk Pinmemberfloppes19-Oct-07 2:47 
GeneralRunning under different Username PinmemberGary Puerini27-Jan-05 9:51 
GeneralLive update Pinmembermangeshdixit23-Dec-04 1:30 
GeneralGrabbing StdOut/StdErr from existing process PinmemberKeith Markfield22-Dec-04 4:16 
QuestionWhat about stdin ? Pinsussr0dy22-Sep-04 9:54 
AnswerRe: What about stdin ? Pinmemberothell25-Sep-04 5:54 
GeneralRe: What about stdin ? Pinsusspblmwithname25-Sep-04 8:04 
Generalidea how to friendly stop a console app PinmemberSamJost31-Jul-04 1:06 
QuestionGetting ALL of the output? PinmemberJCrouch10-Jun-04 8:07 
GeneralThx! Pinmemberschorsch0116-Jan-04 8:52 
Generalerror Pinsusscemcemi19-Dec-03 8:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 1 Sep 2003
Article Copyright 2003 by Mike Mayer
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid