psubsee2003
psubsee2003

Reputation: 8751

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

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.)

Upvotes: 5

Views: 2173

Answers (2)

Tilak
Tilak

Reputation: 30728

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();
    }
}

Upvotes: 4

Marhazk
Marhazk

Reputation: 15

try this, this might be help you, in easy way

private System.Threading.TimerCallback worker;
private System.Threading.Timer workertimer ;
private void worker_DoWork()
{
   //You codes
}
private void StartWorker()
{
   worker = new System.Threading.TimerCallback(worker_DoWork);
   workertimer = new System.Threading.Timer(worker, null, 1000, 1000);
}

private void CancelWorker()
{
    worker.Dispose();
}

Upvotes: -1

Related Questions