C# - Making a Process.Start wait until the process has start-up

前端 未结 12 2117
迷失自我
迷失自我 2020-11-27 17:12

I need to make sure that a process is running before moving on with a method.

The statement is:

Process.Start(\"popup.exe\");

Can y

12条回答
  •  眼角桃花
    2020-11-27 18:10

    I used the EventWaitHandle class. On the parent process, create a named EventWaitHandle with initial state of the event set to non-signaled. The parent process blocks until the child process calls the Set method, changing the state of the event to signaled, as shown below.

    Parent Process:

    using System;
    using System.Threading;
    using System.Diagnostics;
    
    namespace MyParentProcess
    {
        class Program
        {
            static void Main(string[] args)
            {
                EventWaitHandle ewh = null;
                try
                {
                    ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "CHILD_PROCESS_READY");
    
                    Process process = Process.Start("MyChildProcess.exe", Process.GetCurrentProcess().Id.ToString());
                    if (process != null)
                    {
                        if (ewh.WaitOne(10000))
                        {
                            // Child process is ready.
                        }
                    }
                }
                catch(Exception exception)
                { }
                finally
                {
                    if (ewh != null)
                        ewh.Close();
                }
            }
        }
    }
    

    Child Process:

    using System;
    using System.Threading;
    using System.Diagnostics;
    
    namespace MyChildProcess
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    // Representing some time consuming work.
                    Thread.Sleep(5000);
    
                    EventWaitHandle.OpenExisting("CHILD_PROCESS_READY")
                        .Set();
    
                    Process.GetProcessById(Convert.ToInt32(args[0]))
                        .WaitForExit();
                }
                catch (Exception exception)
                { }
            }
        }
    }
    

提交回复
热议问题