2011-04-11 55 views
0

我在解密msdn文檔時遇到了一些麻煩。用WaitForExit調用流程類的正確順序是什麼?

我想調用進程類。如果進程類調用的進程退出,我希望我的代碼退出,但我希望將「StandardOutput」和「StandardError」寫入日誌文件。

如果進程類調用的進程掛起(並且不退出)我希望我的代碼超時並在特定的超時時間後關閉進程,但我仍然希望「StandardOutput」和「StandardError」爲寫入日誌文件。

所以我有這個作爲我的代碼:

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 to do with this yet 
    } 
    finally 
    { 
     try 
     { 
      p.Kill(); 
     } 
     catch { } 
    } 
} 

這是做事的正確方法嗎?

回答

0

不完全是,您需要一個計時器來設置超時。此代碼可能會對您有所幫助:

Process process = Process.Start(startInfo); 

process.EnableRaisingEvents = true; 

bool execTimeout = false; 

// this call back will be called when timer ticks, Timeout for process. 
TimerCallback callBack = (_process) => 
{ 
    // if the process didn't finish exexuting 
    // and the timeout has reached 
    // then kill the process. 
    if (!(_process as Process).HasExited) 
    { 
     execTimeout = true; 
     (_process as 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 the timer. because the process has finished executing. 
timer.Change(Timeout.Infinite, Timeout.Infinite); 

// if the process has finished by timeout [The timer which declared above] 
// or finished normally [success or failed]. 
if (execTimeout) 
{ 
    // Write in log here 
} 
else 
{ 
    string standardOutput = process.StandardOutput.ReadToEnd(); 
    string standardError = process.StandardError.ReadToEnd(); 
} 

祝您好運!

+0

我不明白這個代碼:-(我不知道第8行的含義是什麼,這是一個匿名方法嗎? – Exitos 2011-04-12 10:08:16

+0

那麼,你可以把它作爲一個普通的函數,只要把它拿出來。 – Homam 2011-04-12 11:50:36

相關問題