Creating a thread waits for output without resorting to Thread.Sleep ()

I had a problem trying to wrap my head with what I am doing wrong while trying a simple streaming operation in one of my applications.

Here's what I need: I want the main thread to spawn a separate thread; that a separate thread will open the program, write this program with an argument (file name), and then, as soon as this program closes, the child thread will end and the main thread will be able to continue working. To illustrate, I created a very simple code example. And indeed, it DOES NOT even have a separate thread, it just needs to wait until the program works with it. What am I doing wrong here? Any help would be appreciated!

 class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Opening....");

        var t = new Thread(StartProgram);
        t.Start();
        t.Join();

        Console.WriteLine("Closed");
        Console.ReadLine();
    }

    private static void StartProgram()
    {
        var startInfo = new ProcessStartInfo();
        startInfo.FileName = @"c:\program.exe";
        startInfo.Arguments = @"file.txt";

        var p = Process.Start(startInfo);
        p.WaitForExit();
    }

}
+3
5

? :

static void Main(string[] args)
{
    Console.WriteLine("Opening....");

    StartProgram();

    Console.WriteLine("Closed");
    Console.ReadLine();
}

StartProgram ... ? , - ...

+10

, , , , , :)

. Process.WaitForExit() . , Windows API. program.exe . - WaitForExit(), program.exe, , .

- Microsoft Word. , , , . , msword.exe - , . msword.exe, , . , , , , , . .

. program.exe, , Q & D.

+2

. , , , .

+1

, , ?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Opening....");

        var startInfo = new ProcessStartInfo();
        startInfo.FileName = @"c:\program.exe";
        startInfo.Arguments = @"file.txt";

        var p = Process.Start(startInfo);
        p.WaitForExit();

        Console.WriteLine("Closed");
        Console.ReadLine();
    }

}
+1

, , , . , join(). t.join() Main Thread , t , , .

, - .

0

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


All Articles