2015-06-13 116 views
0

我有一个启动第二个exe的方法。我遇到的问题是,如果我在Visual Studio中处于调试模式,并且在Process.Start调用后直接放置断点,我的第二个应用程序立即启动,但如果我在VS中没有断点或运行我的主C#应用程序在VS之外,通过Process.Start启动我的第二个应用程序最多可能需要两分钟的时间。我的方法是在下面,我把我的断点看到第二个应用程序的立即启动是在“if(null!= _ProcessMine)”行。我把第二个exe文件的启动放在了一个工作线程中,因为当我关闭主exe文件时,我想要关闭第二个exe文件。Process.Start需要很长时间才能启动外部应用程序

public static void RunBtnProcessThread(string processName, String sArgs, Button btn) 
    { 
     // disable the button until we release the newly launched process 
     btn.Enabled = false; 

     BackgroundWorker worker = new BackgroundWorker(); 

     worker.DoWork += (doWorkSender, doWorkArgs) => 
     { 
      ProcessStartInfo startInfo = new ProcessStartInfo(); 
      startInfo.CreateNoWindow = false; 
      startInfo.UseShellExecute = false; 
      startInfo.FileName = processName; 
      startInfo.Arguments = sArgs; 
      try 
      { 
       using (_ProcessMine = Process.Start(startInfo)) 
       { 
        if(null != _ProcessMine) 
         _ProcessMine.WaitForExit(); 
       } 
      } 
      catch (Exception ex) 
      { 
       string _Funk = ReflectionHelper.GetMethodFullName(MethodBase.GetCurrentMethod()); 

       // error 
       Debug.Assert(false, "Error: " + ex.Message); 

       // Log error. 
       TraceUtil.LogException(_Funk, ex); 
      } 

      System.Threading.Thread.Sleep(500); 
     }; 

     worker.RunWorkerCompleted += (completedSender, completedArgs) => 
     { 
      btn.Enabled = true; 

      _ProcessMine)= null; 
     };    

     worker.RunWorkerAsync(); 
    } 
+0

我已经编辑好标题:

public static void RunBtnProcessThread(string processName, String sArgs, Button btn) { // disable the button until we release the newly launched process btn.Enabled = false; ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = processName; startInfo.Arguments = sArgs; try { _ProcessMine = Process.Start(startInfo); _ProcessMine.EnableRaisingEvents = true; _ProcessMine.Exited += (sender, e) => { btn.Invoke((MethodInvoker)delegate { btn.Enabled = true; }); _ProcessMine = null; }; } catch (Exception ex) { string _Funk = ReflectionHelper.GetMethodFullName(MethodBase.GetCurrentMethod()); // error Debug.Assert(false, "Error: " + ex.Message); // Log error. TraceUtil.LogException(_Funk, ex); } } 

你可以使用类似关闭它。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

回答

0

实际上您并不需要针对您的方案使用单独的线程。您可以通过订阅Process.Exited()事件完成同样的事情:

void Form1_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     if (_ProcessMine != null && !_ProcessMine.HasExited) 
     { 
      // Depending on the type of app: 
      _ProcessMine.CloseMainWindow(); 
      // ... or ... 
      _ProcessMine.Kill(); 
     } 
    } 
+0

Idle_mind,试试你的方式相同的结果。是的,它会在第一个应用程序关闭时启动并关闭第二个应用程序,但如果我让它在没有中断点的情况下运行,则会挂起。在“_ProcessMine.EnableRaisingEvents = true;”处放置一个断点并立即打开。它几乎就像我需要某种计时器/闲置那里。我尝试过Thread.Sleep,但那也不起作用。感谢您的关注。 – 67vette427

相关问题