'Return the result while the process is running
I have a program which start a batch process. This batch file is a consuming process and I want to return the result while the process is running. I try to use await and async but nothing works.
result = String.Empty;
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = RunText;
startinfo.Arguments = "cmd";
Process process = new Process();
process.StartInfo = startinfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
while (!process.StandardOutput.EndOfStream)
{
result = process.StandardOutput.ReadLine();//I want to return the result
Console.WriteLine(result);
}
-This is my batch program. The output is 1 if there is a connection with another PC.
@echo off
:begin
for /F "tokens=*" %%L in ('netstat -n ^| find ":3389" ^| find "ESTABLISHED" /c') do (set "VAR=%%L")
echo %VAR%
goto begin
I am beginner with this topics(processes and multi-threading). Any help would be greatly appreciated.
Solution 1:[1]
Use handlers to achieve this:
public static void MyHandler(object process, DataReceivedEventArgs dataReceived)
{
if (!String.IsNullOrEmpty(dataReceived.Data))
{
// do something you want here, for an example
Console.WriteLine(dataReceived.Data);
}
}
And in main method:
//...
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler(MyHandler);
process.Start();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RelativeLayouter |
