Run a sequence of processes

public void ExecuteProcessChain(string[] asProcesses, string sInRedirect, string sOutRedirect) { Process p1 = new Process(); p1.StartInfo.UseShellExecute = false; p1.StartInfo.RedirectStandardOutput = true; p1.StartInfo.FileName = asProcesses[0]; p1.Start(); StreamReader sr = p1.StandardOutput; string s, xxx = ""; while ((s = sr.ReadLine()) != null) Console.WriteLine("sdfdsfs"); //xxx += s+"\n"; p1.StartInfo.RedirectStandardInput = true; p1.StartInfo.RedirectStandardOutput = false; p1.StartInfo.FileName = asProcesses[1]; p1.Start(); StreamWriter sw = p1.StandardInput; sw.Write(xxx); sw.Close(); sr.Close(); } 

I try to execute "calc | calc", but when I do this, it gets stuck in the while ((s = sr.ReadLine()) != null) line while ((s = sr.ReadLine()) != null) and only after closing the calculator while ((s = sr.ReadLine()) != null) code continue. I need both calculators to work together. Do you have an idea how to do this?

+4
source share
2 answers

ReadLine read from the output of the first subtraction. Calc does not send any output. Thus, ReadLine will never return, and therefore the next calculator will not start. When the first calc ends, ReadLine can no longer read from the first calc, so it returns null. After he returns, the code can run a second calc.

You can either not read from the first calculation, or read asynchronously. You can refer to Async ReadLine on how to read asynchronously.

You can also run second calc with p2 before you start calling ReadLine .

+1
source

Why not use threads?

Consider this: put each residue in the stream, and then run both of them. After that, the program waits for them. Only after completing both threads with your tasks (reading data) can you continue.

Remember that streams cannot directly modify data from another stream, so I can suggest using Invoke or static variables, depending on what you might need.

If possible, you can use the Task / Parallel library, which already has some useful methods to help you with this.

A background worker is also a way.

0
source

Source: https://habr.com/ru/post/1342015/


All Articles