Visual C# GUI stops responding when process.WaitForExit(); is used

后端 未结 6 1802
臣服心动
臣服心动 2020-12-12 01:14

I am creating a GUI application using Visual C# 2005 (net framework 2). I use the following code to start a process:

Process process = new Process();
process         


        
6条回答
  •  情话喂你
    2020-12-12 01:24

    the solution for this is using a multi-threading start by adding:

    using System.Threading;

    then look at the code bellow :

        Process process = new Process();
        process.StartInfo = new ProcessStartInfo("app.exe");
        process.StartInfo.WorkingDirectory = "";
        process.StartInfo.Arguments = "some arguments";
    

    //starts a new thread that starts the process so when you call WaitForExit it does not freez the main thread

        Thread th= new Thread(() =>
        {
            process.Start();
            process.WaitForExit();
        });
        th.Start();
    

    if you want to run multiple process back to back it is another case you will need to use something like a List of process look at the code bellow

        List processes = new List();;
    
        Process process = new Process();
        process.StartInfo = new ProcessStartInfo("app.exe");
        process.StartInfo.WorkingDirectory = "";
        process.StartInfo.Arguments = "some arguments";
    
        processes.Add(process); 
    

    // i add another one manually but you can use a loop for exemple

        Process process2 = new Process();
        process.StartInfo = new ProcessStartInfo("app.exe");
        process.StartInfo.WorkingDirectory = "";
        process.StartInfo.Arguments = "some arguments";
    
        processes.Add(process2);
    

    // then you will start them though your thread and the 2nd process will wait till the first finishes without blocking the UI

        Thread th= new Thread(() =>
        {
                for (int i = 0; i < processes.Count; i++)
                {
                        processes[i].Start();
                        processes[i].WaitForExit();
                 }
        });
        th.Start();
    

提交回复
热议问题