Search code examples
c#invalidoperationexception

Perform an action when a process closes


First of all, I'm programming in Windows Forms Application.
As the title describes, I want to perform an action when a process I started, will close.

I've tried at first:

Process s = new Process();  
s.EnableRaisingEvents = true;  
s = Process.Start(processToStart);  
s.Exited += s_Exited;

When I do:

Process s = new Process();  
s = Process.Start(processToStart);  
s.EnableRaisingEvents = true;  
s.Exited += s_Exited;

I get exception of System.InvalidOperationException.

Full exception details:

Additional information: Cross-thread operation not valid: Control 'Main' accessed from a thread other than the thread it was created on.


Solution

  • There are two problems with your original code

    1- You assign a new process to s at s = Process.Start(processToStart);, so you loose s.EnableRaisingEvents = true;

    2- Exited event is called from a thread different than you UI thread. Therefore you should use Invoke to avoid cross thread exception

    Process p = new Process();
    p.EnableRaisingEvents = true;
    p.StartInfo = new ProcessStartInfo() { FileName = processToStart };
    p.Exited += (s, e) =>
    {
        this.Invoke((Action)(() =>
        {
            //your code accesing UI, for ex, 
            this.Text = "Exited";
        }));
    };
    p.Start();
    

    PS: Your current code attaches to Exited event after the process has started. It may happen (with a low probability), that process exits before you attach to the event. Above code is more correct way of doint it.