views:

623

answers:

5

Not to long ago i asked about an error msg that occurred when when app.PriorityClass = ? was before app.start. Apparently the solution which i didnt like was to write it after start.

It worked without much problem until today. I get a "Cannot process request because the process has exited." exception because the process completes quickly enough to not have its priority changed (some of the time). Wrapping a try around this feels bad. What is the real solution? how do i launch a process with low priority ?

            Process app = new Process();
            app.StartInfo.FileName = @"bin\convert.exe";
            app.StartInfo.Arguments = string.Format("{0} -resize 150x150 {1}", filename, thumbName);
            //app.PriorityClass = ProcessPriorityClass.BelowNormal; //No process is associated with this object.
            app.Start();
            //app.PriorityClass = ProcessPriorityClass.BelowNormal; //"Cannot process request because the process has exited."
A: 

Any test you can do is going to immediately be a race condition; if the app exits quickly, the only safe thing I can think of is to use try/catch.

Unless it reads from stdio? In which case you could redirect it and deliberately not close the input stream until you've changed the priority.

Marc Gravell
+1  A: 

Your choices are:

  1. Try to set it and catch the exception if it has already exited.
  2. Check to see if the process has exited first and then try to set it ... and still catch the exception if it has already exited.

Because even when you check, the process could still exit between when you check and when you try to set it. So, really, just go with option #1 because it's less code.

Lee
+1  A: 

Why would you want to avoid catching and exception condition that you know how to deal with at the lowest possible level? If you can set the priority, great! If not, the process has quit and your work is done. I don't think there's any reason to try and avoid appropriately handling the error.

JP Alioto
A: 

You could always use an if statement:

if (!app.HasExited)
{
   app.PriorityClass = ProcessPriorityClass.BelowNormal;
}

I agree with the other answers though, you should still be catching your exceptions and handling them properly anyways.

rie819
There's still a race condition here :)
AakashM
+2  A: 

The solution: start the process suspended, then change the priority, and then resume the process.

This is done in Win32 with CREATE_SUSPENDED in the call to CreateProcess, but unfortunately I don't know the .NET way offhand.

zildjohn01