C# 已终止的进程正在使用GetProcessByName再次返回

C# 已终止的进程正在使用GetProcessByName再次返回,c#,process,C#,Process,在我的c#windows应用程序中,我编写了以下代码,用于在启动c#应用程序之前运行该进程并杀死任何进程,如果在运行c#应用程序时杀死它并再次启动它 //Finding TestApp Process[] pname = Process.GetProcessesByName("TestApp"); If any TesyApp running before kill it if (pname.Length != 0 && this.processId == 0) { for (

在我的c#windows应用程序中,我编写了以下代码,用于在启动c#应用程序之前运行该进程并杀死任何进程,如果在运行c#应用程序时杀死它并再次启动它

//Finding TestApp
Process[] pname = Process.GetProcessesByName("TestApp");
If any TesyApp running before kill it
if (pname.Length != 0 && this.processId == 0)
{
 for (int i = 0; i < pname.Length; i++)
   { 
    pname[i].Kill();
   }
//Again find the TestApp
 pname = Process.GetProcessesByName("TestApp");                        
}
//If not found start the process
if (pname.Length == 0 )
{
---
process.Start();
this.processId = process.Id;
}
//查找TestApp
Process[]pname=Process.GetProcessesByName(“TestApp”);
如果在杀死它之前有任何TesyApp在运行
if(pname.Length!=0&&this.processId==0)
{
for(int i=0;i
我的问题是,在我运行c#应用程序之前,如果任何TestApp(由flex开发的不同应用程序)应用程序正在运行,请杀死它,并由c#重新启动它。如果我调试代码,一切正常。 但如果我不在调试模式下运行我的c#代码, pname[i].Kill();线 pname=Process.GetProcessesByName(“TestApp”);这又是一次发现。因此长度变为1,c#无法启动它并退出if条件。 如果(pname.Length==0) { -- }


关于在
pname[i].Kill()之后使用
pname[i].WaitForExit()
,以确保它已被杀死。i、 e:

if (pname.Length != 0 && this.processId == 0)
{
  for (int i = 0; i < pname.Length; i++)
  { 
    pname[i].Kill();
    pname[i].WaitForExit();
  }
  //Again find the TestApp
  pname = Process.GetProcessesByName("TestApp");                        
}
if(pname.Length!=0&&this.processId==0)
{
for(int i=0;i
Process.Kill
是异步的,因此它不会等待实际的进程被终止

它在调试时工作的事实可能只是因为它需要更多的时间,所以它允许终止进程