Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canceling a Process started via System.Diagnostics.Process.Start()

Tags:

c#

I am writing an application where I have a Process running in a BackgroundWorker. I would like to support cancellation from the user interface, but I don't see an easy way to do this.

The Process is actually a fairly long running command line exe. The output is getting redirected asynchronously via the Progress.OutputDataReceived event and is being used to report progress to the GUI.

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    using (var process = new Process())
    {
        //...

        process.Start()

        //...

        process.WaitForExit();
    }
}

private void CancelWorker()
{
    worker.CancelAsync();
    // where to actually listen for the cancellation???
}

There doesn't appear to be a way to have the process "listen" for any input from the main thread aside from the StandardInput, but that won't work unless the app itself will response to a specific input to abort.

Is there a way to cancel a process based on a cancel request from the main thread?

For the purposes of my of the EXE running in the process, I can just call Process.Close() to exit without any side-effects, but the Process object is only known to the worker_DoWork() method, so I'll need to keep track of the Process instance for cancellation purposes... that's why I'm hoping there might be a better way.

(if it matters, I am targeting .NET 3.5 for compatibility issues.)

like image 929
psubsee2003 Avatar asked Oct 21 '22 20:10

psubsee2003


1 Answers

For cooperative cancellation, you need to listen to BackgroundWorker.CancellationPending in BackgroundWorker.DoWork event.

How to: Use a Background Worker

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    using (var process = new Process())
    {
        //...

        process.Start()

        //...
        while(true)
        { 
            if ((sender as BackgroundWorker).CancellationPending && !process.HasExited)
            {
              process.Kill();
              break;
            }
            Thread.Sleep(100);
         }

        process.WaitForExit();
    }
}
like image 89
Tilak Avatar answered Oct 24 '22 16:10

Tilak