2011-10-06 29 views
2

与我保持一分钟:让一个进程按时间间隔运行另一个进程

进程A是我的主要工作进程。运行时,它处理信息。可能需要30秒到20分钟才能完成。这个过程有多种变化,并不完全稳定。如果它崩溃了,这并不是什么大不了的事情,因为它可以在下次运行时停止。

过程B是我的首发过程。我希望它按给定的时间间隔运行进程A(如每5分钟一次)。如果进程A已经在运行,那么进程B应该等到下一个时间间隔才能尝试。 IE ...

if(!ProcessA.isRunning) 
    ProcessA.Run(); 
else 
    Wait Until Next Interval to try 

过程A或多或少被写入。我认为它将是它自己的.exe,而不是使用多线程来实现这一点。

我的问题是:如何编写运行单独的.exe的进程B,并将其挂接到它,以便检查它是否正在运行?

回答

2

使用GetProcessByName的像这样:

// Get all instances of Notepad running on the local 
// computer. 
Process [] localByName = Process.GetProcessesByName("notepad"); 

如果得到localByName任何东西,则进程仍在运行。

MSDN Documentation.

+0

只希望别人没有一个名为“记事本”的进程。 。 。 –

0

看看在Process类。

使用此类可以检索有关系统中的进程的所有类型的信息。如果您自己启动流程,则不必扫描所有流程,因此可以防止缓慢且容易出错的呼叫。

当有一个Process对象时,可以使用WaitForExit等到它完成。

你可以做的是:

var startOtherProcess = true; 
    while (startOtherProcess) { 
     var watchedProcess = Process.Start("MyProgram.Exe"); 
     watchedProcess.WaitForExit(); 
     if (testIfProcessingFinished) { 
      startOtherProcess = false; 
     } 

    } 
0

这里是下面的代码是如何工作的: 它检查是否指定的进程中运行,如果是它忽略,否则它运行你所需要的。间隔使用System.Timers.Timer

[DllImport("user32.dll")] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    static extern bool SetForegroundWindow(IntPtr hWnd); 

    public void RunProcess() 
    { 
     bool createdNew = true; 
     using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) 
     { 
      if (createdNew) 
      { 
       // Here you should start another process 
       // if it's an *.exe, use System.Diagnostics.Process.Start("myExePath.exe"); 
      } 
      else 
      { 
       Process current = Process.GetCurrentProcess(); 
       foreach (Process process in Process.GetProcessesByName(current.ProcessName)) 
       { 
        if (process.Id != current.Id) 
        { 
         SetForegroundWindow(process.MainWindowHandle); 
         break; 
        } 
       } 
      } 
     } 
    } 
相关问题