I
I
iamserge2020-10-11 13:28:20
C++ / C#
iamserge, 2020-10-11 13:28:20

How to make a permanent background Process in C#?

In general, everything is very simple ...

try
            {

                psi.FileName = @"C:/Users/User/AppData/Local/Programs/Python/Python38-32/python.exe";
                var PyScript = @"Load.py";

                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError = true;
 
                psi.Arguments = $"\"{PyScript}\"";

                var errors = "";
                var output = "";
                using (var process = Process.Start(psi))
                {
                    errors = process.StandardError.ReadToEnd();
                    output = process.StandardOutput.ReadToEnd();
                }

                richTextBox2.AppendText(errors);
                richTextBox2.AppendText(output);

            }

            catch (Exception eU)
            {

                // Сообщение о ошибке
                MessageBox.Show(eU.Message);

                // Информаци о ошибке
                MessageBox.Show(eU.ToString());

            }


from datetime import datetime
import sys
import pytz
import time

j = 0
while(True):
    time.sleep(0.5)
    print("Next step " + str(j))
    j = j + 1
    if(j > 10):
        break


I simplified Python, but in fact it should work for itself even longer, much longer, i.e. hours and periodically give out something about their work. All this happens when you start the C# application, but here's the problem - the application hangs all the time until the script finishes work and I get all the output in one go ....

How to set up work in the background, but not lose connection with the script and get the result of its work ? Background i.e. do not "hang" the interface and give the application the highest priority, and the result from the script is the required minimum, i.e. those nanoseconds it takes to add a couple of lines to richTextBox2...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tsiren Naimanov, 2020-10-11
@ImmortalCAT

Look towards the Background Process
And there is also a Quartz.NET library

D
Dmitry Belyaev, 2020-10-11
@bingo347

Because the ReadToEnd method blocks the thread until it has read the entire stream to the end
. Use ReadLineAsync or ReadToEndAsync to read data asynchronously.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question