Process.Start in BackgroundWorker C#

Fred B picture Fred B · Apr 6, 2013 · Viewed 11.6k times · Source

I'm having the worst time wrapping my head around threads/background processes. My issues seem common enough to a certain point but I've yet to find a good example that meets my needs.

The classic example goes like this:
My UI freezes when a certain long running task/process runs -I want to be able to at least move/minimize the UI.

Classic replies include Threading and Task Factories and BackgroundWorker solutions. but no matter how I implement them I get poor results.

In my program, I'm executing another application and waiting for it to finish. For the sake of simplicity let's say I'm doing it like so:

            Process p = Process.Start("notepad.exe somefile.txt");
            p.WaitForExit();
            //read somefile.txt

Clearly my application UI would hang while WaitForExit() grinds away waiting for me to close notepad.

I've attempted a number of suggested means around this but I get painted into one of two corners:

  1. My interface still hangs, then reads somefile.txt just fine when I close notepad.
  2. The Process (Notepad) runs fine but my application reads somefile.txt immediately before I have closed notepad (So I guess it's running asynchronously)

Most examples I see involve counting to a high number -simple but not quite what I'm doing. Firing off this "external" process complicates things a bit.

Thanks for your time and consideration!!

Answer

Mathieu Guindon picture Mathieu Guindon · Apr 6, 2013

BackgroundWorker seems appropriate here; it should be configured something along those lines:

var worker = new BackgroundWorker();
worker.WorkerReportsProgress = false;
worker.WorkerSupportsCancellation = false;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();

Then you have the handlers:

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    //start notepad process here.
}

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //read somefile.txt here.
}