简体   繁体   中英

Process.Start in BackgroundWorker C#

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!!

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

From the sounds of things your application isn't running the Process.WaitForExit call on a separate thread otherwise there wouldn't be any hanging.

BackgroundWorker , Thread and the ThreadPool are all useful tools, but they can be difficult and cumbersome to work with and get right, the Task Parallel Library with System.Threading.Task has somewhat "superseded" using threads directly for most operations you need to perform asynchronously.

See: Threads and the new Task library in C#

So your code becomes.

Task.Factory.StartNew(() =>
{
   var proc = new Process("...");
   proc.WaitForExit();
   File.Read("...");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM