C # Input and output redirection method two: asynchronous process

Source: Internet
Author: User
Tags try catch

Using events and delegates, the process has 2 events outputdatareceived, errordatareceived can be used to redirect standard output and standard error output;

It is important to note that inputdatareceived is not a process event, so standard input cannot be so redirected;

Need to add before use: Using System.Diagnostics; can use process

Step one: Identify essential ingredients

1 Process startinfostartinfo =newprocessstartinfo (. exe); 2 true;   // do not create a window 3 false ; 4 // do not use system shell to start, redirect output must be set to False 5 true // REDIRECT output, 6 true;

Step two: Using the try Catch block

1  Try2 {3Processprocess =Process.Start (startinfo);4Process. Outputdatareceived + = (s, _e) =Console.WriteLine (_e.data);5Process. Errordatareceived + = (s, _e) =Console.WriteLine (_e.data);6     //when EnableRaisingEvents is true, process exits with the following delegate function called7Process. Exited + = (s, _e) = Console.WriteLine ("Exited with"+_process. ExitCode);8Process. EnableRaisingEvents =true;9 process. Beginoutputreadline ();Ten process. Beginerrorreadline (); One process. WaitForExit (); A } - Catch(Exception e) - { the Console.WriteLine (ex. Message); -}

It is important to note that asynchronous and synchronous read operations cannot be mixed with the same redirect stream.

After you open the redirect stream for a Process in asynchronous or synchronous mode, all further read operations on the stream must be in the same mode.

For example, do not call Beginoutputreadline after the standardoutput stream and then call ReadLine, and vice versa.

However, you can read two different streams in different modes. For example, you can call beginoutputreadlineFirst, and then call ReadLinefor the standarderror stream.

C # Input and output redirection method two: asynchronous process

Related Article

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.