c# - What is the correct order for calling the process class with WaitForExit? -


i'm having bit of trouble de-ciphering msdn documentation.

i want call process class. if process process class calls exits want code exit want "standardoutput" , "standarderror" written log file.

if process process class calls hangs (and doesnt exit) want code timeout , close process after timeout 'time' still want "standardoutput" , "standarderror" written log file.

so have code:

using (process p = new process()) {     p.startinfo.filename = exepatharg;     p.startinfo.redirectstandardoutput = true;     p.startinfo.redirectstandarderror = true;     p.startinfo.arguments = argumentsarg;     p.startinfo.useshellexecute = false;     p.startinfo.createnowindow = true;      try     {         p.start();         p.waitforexit(timetowaitforprocesstoexit);          streamreader standardoutput = p.standardoutput;         streamreader standarderror = p.standarderror;          retdirects.add("standardoutput", standardoutput.readtoend());         retdirects.add("standarderror", standarderror.readtoend());         }     catch (exception ex)     {         //nothing yet     }         {         try         {             p.kill();         }         catch { }     } } 

is right way of doing things?

not exactly, need timer set timeout. code might you:

process process = process.start(startinfo);  process.enableraisingevents = true;  bool exectimeout = false;  // call called when timer ticks, timeout process. timercallback callback = (_process) => {     // if process didn't finish exexuting     // , timeout has reached      // kill process.     if (!(_process process).hasexited)     {         exectimeout = true;         (_process process).kill();     } };  int timeout = 4000; // 4 seconds system.threading.timer timer = new system.threading.timer(callback,                                       process, timeout, timeout.infinite);  // block untill finishing executing [sync calling] process.waitforexit();  // disable timer. because process has finished executing. timer.change(timeout.infinite, timeout.infinite);  // if process has finished timeout [the timer declared above] // or finished [success or failed]. if (exectimeout) {     // write in log here } else {     string standardoutput = process.standardoutput.readtoend();     string standarderror = process.standarderror.readtoend(); } 

good luck!


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -