0

I've written the following code to loop around a load of data table rows and generate a PDF if it doesn't already exist. It works, but it launches the wkhtmltoPDFs all in one go so 30 processes get started and kill the server, d'oh!

What's the best way to launch one process at a time and not start the second until the previous one has run?

   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

                }

            } 
MissCoder87
  • 2,669
  • 10
  • 47
  • 82

1 Answers1

0

Process.Start returns a Process object, which lets you monitor the state of the newly-created process.

A simple, blocking way would be to have each worker wait for the process to exit

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

A better way would be to use the Exited event handler to monitor when the process exits.

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