2014-09-10 62 views
0

我已經編寫了以下代碼來循環加載數據錶行,並生成PDF(如果它尚不存在)。它可以工作,但它一次性啓動wkhtmltoPDF,所以30個進程開始並終止服務器,噢!如何排隊系統進程啓動

什麼是一次啓動一個進程而不是從第二個啓動直到前一個進程運行的最佳方式?

DB db = new DB(); 
      DataTable dtPosters = db.GetDataTable("select * from Invoices where PDFGenerated <> 1 or PDFGenerated is Null"); 

      foreach (DataRow DR in dtPosters.Rows) 
      { 
       //Generate Poster, If exsists (Don't!) 
       Directory.CreateDirectory(string.Format("D:\\Invoices\\")); 
       string FilePath = string.Format("D:\\Invoices\\{0}.pdf", DR["InvoiceNumber"].ToString()); 
       if (!File.Exists(FilePath)) 
       { 
        string CMD = string.Format("C:\\Services\\Automafe\\wkhtmltoPDF.exe http://invoicegen/viewinvoice.aspx?InvoiceNumber={0} {1}", DR["InvoiceNumber"].ToString(), FilePath); 
        System.Diagnostics.Process.Start("cmd", "/c " + CMD); 

       } 
       else 
       { 

        //Update the DB 

       } 

      } 
+0

您可以添加事件偵聽器時看到的過程是封閉的,如下:http://stackoverflow.com/a/8455896/575530 – dumbledad 2014-09-10 13:27:13

+0

這一個甚至更好:'process.WaitForExit()'HTTP ://stackoverflow.com/a/3147920/575530 – dumbledad 2014-09-10 13:29:28

回答

0

Process.Start返回一個Process對象,它允許您監視新創建的進程的狀態。

簡單,堵的辦法是讓每個工人wait for the process to exit

var myProcess = System.Diagnostics.Process.Start("cmd", "/c " + CMD); 
myProcess.WaitForExit(); 

一個更好的辦法是使用Exited event handler當監視的進程退出。

var myProcess = System.Diagnostics.Process.Start("cmd", "/c " + CMD); 
myProcess.Exited += myProcessFinishedHandler;