我有以下功能:起動過程並不總是開始
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正在清理乾淨。只是一個猜測。
我很感謝你的幫助。
我放了幾個睡覺,看看它是否發生得太快。
您可以使用Process.GetProcessesByName:http://msdn.microsoft.com/en-us/l ibrary/system.diagnostics.process.getprocessesbyname.aspx – Misha 2012-07-12 20:30:19
此外,而不是檢查如果Process.GetProcesses ..返回具有相同名稱的任何進程,您可以檢查它是否啓動後processToExecute .HasExited?如果與當前正在運行的進程進行比較,則可能還希望在搜索時使用該進程的Id,因爲可能有多個進程使用相同的名稱運行 – Misha 2012-07-12 20:32:07
另外,您可能希望在檢查進程名稱時使用.Equals而不是.Contains: bool exists = Process.GetProcesses()。Any(p => p.ProcessName.Equals(processName,StringComparison.OrdinalIgnoreCase)); – Misha 2012-07-12 20:34:46