Process.BeginOutputReadLine Methode
Definitie
Belangrijk
Bepaalde informatie heeft betrekking op een voorlopige productversie die aanzienlijk kan worden gewijzigd voordat deze wordt uitgebracht. Microsoft biedt geen enkele expliciete of impliciete garanties met betrekking tot de informatie die hier wordt verstrekt.
Begint asynchrone leesbewerkingen voor de omgeleide StandardOutput stroom van de toepassing.
public:
void BeginOutputReadLine();
[System.Runtime.InteropServices.ComVisible(false)]
public void BeginOutputReadLine();
public void BeginOutputReadLine();
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.BeginOutputReadLine : unit -> unit
member this.BeginOutputReadLine : unit -> unit
Public Sub BeginOutputReadLine ()
- Kenmerken
Uitzonderingen
De eigenschap RedirectStandardOutput is false.
– of –
Er wordt al een asynchrone leesbewerking uitgevoerd op de StandardOutput stream.
– of –
De StandardOutput stream is gebruikt door een synchrone leesbewerking.
Voorbeelden
In het volgende voorbeeld ziet u hoe u asynchrone leesbewerkingen uitvoert op de omgeleide StandardOutput stroom van de sort opdracht. De sort opdracht is een consoletoepassing die tekstinvoer leest en sorteert.
In het voorbeeld wordt een gebeurtenisdelegen voor de SortOutputHandler gebeurtenis-handler gemaakt en gekoppeld aan de OutputDataReceived gebeurtenis. De gebeurtenishandler ontvangt tekstregels van de omgeleide StandardOutput stroom, formatteert de tekst en schrijft de tekst naar het scherm.
// Define the namespaces used by this sample.
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;
namespace ProcessAsyncStreamSamples
{
class SortOutputRedirection
{
// Define static variables shared by class methods.
private static StringBuilder sortOutput = null;
private static int numOutputLines = 0;
public static void SortInputListText()
{
// Initialize the process and its StartInfo properties.
// The sort command is a console application that
// reads and sorts text input.
Process sortProcess = new Process();
sortProcess.StartInfo.FileName = "Sort.exe";
// Set UseShellExecute to false for redirection.
sortProcess.StartInfo.UseShellExecute = false;
// Redirect the standard output of the sort command.
// This stream is read asynchronously using an event handler.
sortProcess.StartInfo.RedirectStandardOutput = true;
sortOutput = new StringBuilder();
// Set our event handler to asynchronously read the sort output.
sortProcess.OutputDataReceived += SortOutputHandler;
// Redirect standard input as well. This stream
// is used synchronously.
sortProcess.StartInfo.RedirectStandardInput = true;
// Start the process.
sortProcess.Start();
// Use a stream writer to synchronously write the sort input.
StreamWriter sortStreamWriter = sortProcess.StandardInput;
// Start the asynchronous read of the sort output stream.
sortProcess.BeginOutputReadLine();
// Prompt the user for input text lines. Write each
// line to the redirected input stream of the sort command.
Console.WriteLine("Ready to sort up to 50 lines of text");
String inputText;
int numInputLines = 0;
do
{
Console.WriteLine("Enter a text line (or press the Enter key to stop):");
inputText = Console.ReadLine();
if (!String.IsNullOrEmpty(inputText))
{
numInputLines++;
sortStreamWriter.WriteLine(inputText);
}
}
while (!String.IsNullOrEmpty(inputText) && (numInputLines < 50));
Console.WriteLine("<end of input stream>");
Console.WriteLine();
// End the input stream to the sort command.
sortStreamWriter.Close();
// Wait for the sort process to write the sorted text lines.
sortProcess.WaitForExit();
if (numOutputLines > 0)
{
// Write the formatted and sorted output to the console.
Console.WriteLine($" Sort results = {numOutputLines} sorted text line(s) ");
Console.WriteLine("----------");
Console.WriteLine(sortOutput);
}
else
{
Console.WriteLine(" No input lines were sorted.");
}
sortProcess.Close();
}
private static void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
// Collect the sort command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
numOutputLines++;
// Add the text to the collected output.
sortOutput.Append(Environment.NewLine +
$"[{numOutputLines}] - {outLine.Data}");
}
}
}
}
namespace ProcessAsyncStreamSamples
{
class ProcessSampleMain
{
/// The main entry point for the application.
static void Main()
{
try
{
SortOutputRedirection.SortInputListText();
}
catch (InvalidOperationException e)
{
Console.WriteLine("Exception:");
Console.WriteLine(e);
}
}
}
}
// Define the namespaces used by this sample.
open System
open System.Text
open System.Diagnostics
// Define variables shared by class methods.
let mutable sortOutput = StringBuilder()
let mutable numOutputLines = 0;
let sortOutputHandler (sendingProcess: obj) (outLine: DataReceivedEventArgs) =
// Collect the sort command output.
if String.IsNullOrEmpty outLine.Data |> not then
numOutputLines <- numOutputLines + 1
// Add the text to the collected output.
sortOutput.Append(Environment.NewLine + $"[{numOutputLines}] - {outLine.Data}") |> ignore
let sortInputListText () =
// Initialize the process and its StartInfo properties.
// The sort command is a console application that
// reads and sorts text input.
let sortProcess = new Process();
sortProcess.StartInfo.FileName <- "Sort.exe"
// Set UseShellExecute to false for redirection.
sortProcess.StartInfo.UseShellExecute <- false;
// Redirect the standard output of the sort command.
// This stream is read asynchronously using an event handler.
sortProcess.StartInfo.RedirectStandardOutput <- true;
sortOutput <- StringBuilder();
// Set our event handler to asynchronously read the sort output.
sortProcess.OutputDataReceived.AddHandler sortOutputHandler
// Redirect standard input as well. This stream
// is used synchronously.
sortProcess.StartInfo.RedirectStandardInput <- true;
// Start the process.
sortProcess.Start() |> ignore
// Use a stream writer to synchronously write the sort input.
let sortStreamWriter = sortProcess.StandardInput;
// Start the asynchronous read of the sort output stream.
sortProcess.BeginOutputReadLine();
// Prompt the user for input text lines. Write each
// line to the redirected input stream of the sort command.
printfn "Ready to sort up to 50 lines of text"
let mutable inputText = ""
let mutable numInputLines = 0
while String.IsNullOrEmpty inputText do
printfn "Enter a text line (or press the Enter key to stop):"
inputText <- Console.ReadLine()
if String.IsNullOrEmpty inputText |> not then
numInputLines <- numInputLines + 1
sortStreamWriter.WriteLine inputText
printfn "<end of input stream>\n"
// End the input stream to the sort command.
sortStreamWriter.Close()
// Wait for the sort process to write the sorted text lines.
sortProcess.WaitForExit()
if numOutputLines > 0 then
// Write the formatted and sorted output to the console.
printfn $" Sort results = {numOutputLines} sorted text line(s) "
printfn "----------"
printfn $"{sortOutput}"
else
printfn " No input lines were sorted."
sortProcess.Close();
// The main entry point for the application.
do
try
sortInputListText ()
with :? InvalidOperationException as e ->
printfn "Exception:"
printfn $"{e}"
' Define the namespaces used by this sample.
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Namespace ProcessAsyncStreamSamples
Class ProcessAsyncOutputRedirection
' Define static variables shared by class methods.
Private Shared sortOutput As StringBuilder = Nothing
Private Shared numOutputLines As Integer = 0
Public Shared Sub SortInputListText()
' Initialize the process and its StartInfo properties.
' The sort command is a console application that
' reads and sorts text input.
Dim sortProcess As New Process()
sortProcess.StartInfo.FileName = "Sort.exe"
' Set UseShellExecute to false for redirection.
sortProcess.StartInfo.UseShellExecute = False
' Redirect the standard output of the sort command.
' Read the stream asynchronously using an event handler.
sortProcess.StartInfo.RedirectStandardOutput = True
sortOutput = New StringBuilder()
' Set our event handler to asynchronously read the sort output.
AddHandler sortProcess.OutputDataReceived, AddressOf SortOutputHandler
' Redirect standard input as well. This stream
' is used synchronously.
sortProcess.StartInfo.RedirectStandardInput = True
' Start the process.
sortProcess.Start()
' Use a stream writer to synchronously write the sort input.
Dim sortStreamWriter As StreamWriter = sortProcess.StandardInput
' Start the asynchronous read of the sort output stream.
sortProcess.BeginOutputReadLine()
' Prompt the user for input text lines. Write each
' line to the redirected input stream of the sort command.
Console.WriteLine("Ready to sort up to 50 lines of text")
Dim inputText As String
Dim numInputLines As Integer = 0
Do
Console.WriteLine("Enter a text line (or press the Enter key to stop):")
inputText = Console.ReadLine()
If Not String.IsNullOrEmpty(inputText) Then
numInputLines += 1
sortStreamWriter.WriteLine(inputText)
End If
Loop While Not String.IsNullOrEmpty(inputText) AndAlso numInputLines < 50
Console.WriteLine("<end of input stream>")
Console.WriteLine()
' End the input stream to the sort command.
sortStreamWriter.Close()
' Wait for the sort process to write the sorted text lines.
sortProcess.WaitForExit()
If Not String.IsNullOrEmpty(numOutputLines) Then
' Write the formatted and sorted output to the console.
Console.WriteLine($" Sort results = {numOutputLines} sorted text line(s) ")
Console.WriteLine("----------")
Console.WriteLine(sortOutput)
Else
Console.WriteLine(" No input lines were sorted.")
End If
sortProcess.Close()
End Sub
Private Shared Sub SortOutputHandler(sendingProcess As Object,
outLine As DataReceivedEventArgs)
' Collect the sort command output.
If Not String.IsNullOrEmpty(outLine.Data) Then
numOutputLines += 1
' Add the text to the collected output.
sortOutput.Append(Environment.NewLine +
$"[{numOutputLines}] - {outLine.Data}")
End If
End Sub
End Class
End Namespace
Namespace ProcessAsyncStreamSamples
Class ProcessSampleMain
' The main entry point for the application.
Shared Sub Main()
Try
ProcessAsyncOutputRedirection.SortInputListText()
Catch e As InvalidOperationException
Console.WriteLine("Exception:")
Console.WriteLine(e)
End Try
End Sub
End Class 'ProcessSampleMain
End Namespace 'Process_AsyncStream_Sample
Opmerkingen
De StandardOutput stream kan synchroon of asynchroon worden gelezen. Methoden zoals Read, ReadLineen ReadToEnd voeren synchrone leesbewerkingen uit op de uitvoerstroom van het proces. Deze synchrone leesbewerkingen worden pas voltooid als de bijbehorende Process schrijfbewerkingen naar StandardOutput de stream zijn voltooid of de stream worden gesloten.
Start daarentegen BeginOutputReadLine asynchrone leesbewerkingen op de StandardOutput stream. Deze methode maakt een aangewezen gebeurtenis-handler mogelijk voor de stroomuitvoer en keert onmiddellijk terug naar de aanroeper, die ander werk kan uitvoeren terwijl de stroomuitvoer wordt omgeleid naar de gebeurtenis-handler.
Volg deze stappen om asynchrone leesbewerkingen StandardOutput uit te voeren voor een Process :
Stel UseShellExecute in op
false.Stel RedirectStandardOutput in op
true.Voeg uw gebeurtenis-handler toe aan de OutputDataReceived gebeurtenis. De gebeurtenis-handler moet overeenkomen met de handtekening van de System.Diagnostics.DataReceivedEventHandler gemachtigde.
Start de Process.
Bel BeginOutputReadLine naar de Process. Met deze aanroep worden asynchrone leesbewerkingen gestart op StandardOutput.
Wanneer asynchrone leesbewerkingen worden gestart, wordt de gebeurtenis-handler telkens aangeroepen wanneer de bijbehorende Process tekstregel naar StandardOutput de stroom schrijft.
U kunt een asynchrone leesbewerking annuleren door aan te roepen CancelOutputRead. De leesbewerking kan worden geannuleerd door de beller of door de gebeurtenis-handler. Na het annuleren kunt u opnieuw bellen BeginOutputReadLine om asynchrone leesbewerkingen te hervatten.
Note
U kunt asynchrone en synchrone leesbewerkingen niet combineren in een omgeleide stream. Zodra de omgeleide stroom van een stroom Process is geopend in de asynchrone of synchrone modus, moeten alle verdere leesbewerkingen op die stream zich in dezelfde modus bevinden. Volg BeginOutputReadLine bijvoorbeeld niet met een aanroep naar ReadLine de StandardOutput stream of omgekeerd. U kunt echter twee verschillende streams in verschillende modi lezen. U kunt bijvoorbeeld bellen BeginOutputReadLine en vervolgens bellen ReadLine naar de StandardError stream.