". NET deep breathing" starts a process and gets status information in real time

Source: Internet
Author: User

Both the Earth man and the Martians know that the process class can either get the running processes or start a new process. In 79.77% applications, we just have to let the target process start smoothly, and as far as it executes, there is no error, when the exit is no matter.

However, in some cases, after starting a new process, you also want to be able to transfer data to the target process or to read the information from the new process in real time. For example, to start an installer, the installer writes the installation progress to the standard stream, and the caller can read the progress from the standard stream in order to achieve real-time monitoring of the installation progress.

The process class exposes three standard stream properties:

standardinput--the input stream. The type is writer, why is writer, because this standard flow is relative to the process being started, flow direction is from the caller to the target process, so is to write data, the content is sent to the target process.

standardoutput--the output stream. That is, the target process external output content, flow direction is from the target process to the caller, so to the caller, is read, so its type is reader.

The standarderror--is similar to the input stream, except that it is dedicated to output errors. The error message is the output of the target process, so it is the reader for the caller.

In summary, as long as the new process is started, from the StandardOutput property in a StreamReader object, and then build a loop, constantly read from the stream, you can get the latest state in real time.

In fact, there is a better way to do this, the process class has a Beginoutputreadline method, after the call, will automatically read the data asynchronously, once the target process to receive the data returned, it will cause outputdatareceived. Therefore, we can receive real-time information in the code as long as the event is processed.

Let's make an example. Suppose I get a program that is only responsible for installing in the background, and each time a progress is processed, the progress information is written to the standard stream so that the caller can monitor the progress of the installation on the fly.

The project that is called is completed first, and the project type is the Windows Application project.

Regardless of it, anyway is a standard. exe file, this project I first built a blank project, and then manually set.

Each executable program must have at least one main method. The main processing code is done here, as long as the main method executes, the process exits.

        Static voidMain () {StreamWriter writer=NULL; Stream OutStream=Console.openstandardoutput (); Writer=NewStreamWriter (OutStream); intn =0;  while(N <= -) {Thread.Sleep ( -); Writer.                WriteLine (n); Writer.                Flush (); N++; } writer.            Close (); Environment.exitcode=0; }

This uses the console class, do not think it can only play console application, in fact, the console class also includes the operation of the standard input and output. To call the Openstandardoutput method to get the standard output stream, you can then write the content.

Because the Standaroutput property or outputdatareceived event of the process class is passed with a string, we also use StreamWriter to write the data in the above code.

Note, however, that you must remember to flush once every time you write, so that the contents of the write will be sent to the caller in a timely manner. If you do not flush, the written content is placed in the buffer, the direct stream is closed or the flush is executed before it is actually sent to the standard stream, so the flush method is called every time you write to ensure that the caller receives the message in real time.

The last line Environment.exitcode = 0 indicates that the process exits with exit code 0, which exits normally. Because this main is returned void, it should be set with the ExitCode of the Enviroment class. Of course, you can also change the main method to return a value of type int, then return directly to 0.

Well, the called Process Project completes and now does the caller project, which is a WPF project. In this era, writing Windows desktop applications should take precedence over WPF, because WPF is a top-level thing.

The XAML code is not pasted, directly speaking the core code.

I used a progress bar to show progress in real time, and the Outputdatareceived event of the process class was thrown asynchronously, and to update the progress bar in event handling, a proxy call was required with dispatcher.

However, in this case, it is not necessary, because there is a very NX class, specifically to deal with the progress of the PROGRESS<T>, this class can bind a callback delegate, use it to update the UI is not required dispatcher to dispatch.

            iprogress<int> progress;             New progress<int> (p = +            {                = p;            });

When declaring a variable, the Iprocess<t> interface is used to declare that T is the type that represents the progress, the progress class is the display implementation of the Iprogress interface, in order to be able to directly call the report method reporting progress, Variables should be declared with the Iprogress interface.

The following code initiates the process that was just written and monitors the status information.

Process p =NewProcess (); p.StartInfo.FileName=".. \\.. \\.. \\Demo\\bin\\Debug\\Demo.exe"; P.startinfo.useshellexecute=false;//must be falseP.startinfo.redirectstandardoutput =true; P.startinfo.createnowindow=true; p.EnableRaisingEvents=true;//must be Truep.outputdatareceived+=ondatareceived; P.exited+=onexited;            P.start (); P.beginoutputreadline ();

After instantiating process, to set startinfo related parameters, filename is the exe file to execute the process.

Attention:

The UseShellExecute must be false, otherwise the standard cannot be read in the code.

The redirectstandardoutput must be true so that we can access the standard stream in the code.

EnableRaisingEvents must be true in order for outputdatareceived and exited to be raised

event, otherwise the event does not occur.

CreateNoWindow represents the window that does not display the target program, this is your own look, I do not let it show the window, because this program does not have a window.

Be sure to call the Beginoutputreadline method after the Start method, and be sure to handle the Outputdatareceived event before the start and Beginoutputreadline method calls. Why, think about it, it's too easy, don't take off your pants, unless you don't wear pants.

Read the data in the Ondatareceived method and convert it to the int type, because the project above has an int value written into the stream, so the value read here can be converted to int type.

        Private void Ondatareceived (object  sender, Datareceivedeventargs e)        {            int p =  Convert.ToInt32 (e.data);            Progress. Report (P);        }

The report method that calls iprogress<t> directly reports progress.

Originally, it was possible to call the System.Diagnostics.Process.WaitForExit () method to wait for the process to execute, but since this method was called synchronously, it would have caused the UI thread to jam, causing the UI to fail to respond immediately and experience bad. So instead of handling the exited event, this event will be called asynchronously after the process exits, and will not cause the UI thread to jam, so it's better to handle it.

Now, running the example will look at the following effect.

Sample code

". NET deep breathing" starts a process and gets status information in real time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.