2012-07-12 97 views
1

我有以下功能:起動過程並不總是開始

public static void ExecuteNewProcess(string fileToExecute, Action<string> writeToConsole) 
{ 
    ProcessStartInfo startInfo = new ProcessStartInfo(fileToExecute); 
    Process processToExecute = new Process(); 

    startInfo.UseShellExecute = true; 
    processToExecute.StartInfo = startInfo; 

    if (!File.Exists(fileToExecute)) 
    { 
     throw new FileNotFoundException("File not found for execution"); 
    } 

    if (processToExecute.Start()) 
    { 
     Thread.Sleep(6000); 
     Process[] procs = Process.GetProcesses(); 

     if (IsProcessOpen(Path.GetFileNameWithoutExtension(fileToExecute))) 
     { 
      writeToConsole(fileToExecute + " launched successfully..."); 
     } 
     else 
     { 
      writeToConsole(fileToExecute + " started but not found."); 
      throw new Exception("Application started butnot found running...Delay = 6000, File Name = " + Path.GetFileNameWithoutExtension(fileToExecute));    
     } 

    } 
    else 
    { 
     writeToConsole("Error Launching application: " + fileToExecute); 
     throw new Exception("Application did not launch " + fileToExecute); 
    } 

} 

private static bool IsProcessOpen(string name) 
{ 

    foreach (Process clsProcess in Process.GetProcesses()) 
    { 

     if (clsProcess.ProcessName.Contains(name)) 
     { 

      return true; 
     } 
    } 

    return false; 
} 

所以問題是,有時我的應用程序,我想開始使用此功能沒有啓動(它開始的大約80%時間)。不過,我會通過檢查代碼的一部分來確保它的啓動和輸出。我不確定它爲什麼不開始。當我看到它沒有開始確定它有效的exe文件時,我雙擊該應用程序。它始終是,並開始很好。我也嘗試過使用shell而不使用shell。沒有不同。

我在想,在應用程序成功啓動之前,processToExecute正在清理乾淨。只是一個猜測。

我很感謝你的幫助。

我放了幾個睡覺,看看它是否發生得太快。

+0

您可以使用Process.GetProcessesByName:http://msdn.microsoft.com/en-us/l ibrary/system.diagnostics.process.getprocessesbyname.aspx – Misha 2012-07-12 20:30:19

+0

此外,而不是檢查如果Process.GetProcesses ..返回具有相同名稱的任何進程,您可以檢查它是否啓動後processToExecute .HasExited?如果與當前正在運行的進程進行比較,則可能還希望在搜索時使用該進程的Id,因爲可能有多個進程使用相同的名稱運行 – Misha 2012-07-12 20:32:07

+0

另外,您可能希望在檢查進程名稱時使用.Equals而不是.Contains: bool exists = Process.GetProcesses()。Any(p => p.ProcessName.Equals(processName,StringComparison.OrdinalIgnoreCase)); – Misha 2012-07-12 20:34:46

回答

0

原因的20%的時間當進程啓動您的應用程序不會顯示出來,因爲時間的應用程序需要加載之前,我們看到的用戶界面

所以他們有兩個方法,通過它,你也許能夠實現它

1. start the process - > process.Start(); And then process.WaitForInputIdle();

OR

2. start the process - > process.Start(); And then Thread.Sleep(1000); 
    //make sure you give reasonable milliseconds 
+0

我已經實現了第二個選項...請檢查上面的代碼。 if(processToExecute.Start()) Thread.Sleep(6000); – 2012-07-12 21:18:53

+0

哦,是的:)你有沒有嘗試第一個 – HatSoft 2012-07-12 21:21:37

+0

好吧,我試過#1,它沒有工作。實際上,我把線頭拔出,現在每次都不啓動。我把WaitForInputIdle()放在他們的位置。我仍然得到了檢查的代碼部分,它確實看到啓動過程。只是似乎死... – 2012-07-12 21:37:28