简体   繁体   中英

How to wait for a console process to complete BEFORE running the other console process in wpf applications?

I have 2 external process to run(2 console exe) that provide output to console. I am running these apps on wpf application. I capture console output and use it as input.

here how i do 1. run first process. capture the console output. 2. do some work using the first process output. 3. run the second process after i have the do some work output.

the problem i am having is i have to wait for the other process to finish and use its output before i can run the other process. By the time i want to run the second process, the first process havent been finished.

public MainWindow()
{
    InitializeComponent();
    ExtProcess1();
    ExtProcess2();  //this is executed before ExtProcess1 OutputDataReceived is completely captured
    Instance = this;
}

public static void ExtProcess1()
{
    Process process = new Process();
    process.EnableRaisingEvents = true;
    process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
    process.Exited += new EventHandler(process_Exited);
    process.StartInfo.FileName = "test.exe";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.CreateNoWindow = true;
    process.Start();
    process.PriorityClass = ProcessPriorityClass.RealTime;
    process.BeginOutputReadLine();
    process.WaitForExit();
}

static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    if (MainWindow.Instance.lbLog.Dispatcher.Thread == Thread.CurrentThread)
    {
        String s = (String)e.Data;
        MainWindow.Instance.lbLog.Items.Add(s);
    }
    else
    {
        MainWindow.Instance.lbLog.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
            new EventHandler<DataReceivedEventArgs>(corePingPid_OutputDataReceived), sender, new object[] { e });
    }
}

How do i force the wpf application to wait for the first process BEFORE running the second process?

Assuming you are using Process class to execute and capture output for console, you can use Process.WaitForExit method. It will block the current thread till the process finish the execution. There is another overload that can block the current thread till the process finishes or specified timeout period elapsed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM