title: Parallel processing to create PDFs
body: <p>What I want to achieve is to do multitreading to generate invoices using iTextSharp assembly.</p>
  
  <p>In my understanding in using <code>Parallel.ForEach</code> is that it will take an IEnumerable source and delegate that to different threads.</p>
  
  <p>Now the issue that I have is that 1 process is trying to access a file that is being used by another process.</p>
  
  <blockquote>
    <p><em>The process cannot access the file '...\Invoices\INV0000089576PPN.pdf' because it is being used by
    another process.</em></p>
  </blockquote>
  
  <p>How can I prevent that from happening?</p>
  
  <p><strong>Threading Process</strong></p>
  
  <pre><code>Task task = new Task(() =&gt;
     {
        Parallel.ForEach(orders, currentOrder =&gt;
        {
                  LiveTrainingEntities db = new LiveTrainingEntities();
                  var trans = db.Transactions.SingleOrDefault(x =&gt; x.fTransactionID == currentOrder.TransactionID);
  
                  if (trans != null)
                  {
                      var labOrderInvoices = GetLabOrderInvoices(trans.Practices.fPracticeID, currentOrder.TaxInvoiceNumber);
                      CreateLabOrderInvoice(PopulateHTML(labOrderInvoices), currentOrder.TaxInvoiceNumber);
  
                      Console.WriteLine("Processing {0} on thread {1}", currentOrder.TaxInvoiceNumber,
                                  Thread.CurrentThread.ManagedThreadId);
  
                      //orders.Remove(currentOrder);
         }
     });
  });
  task.Start();
  task.Wait();
  </code></pre>
  
  <p><strong>PDF Method</strong></p>
  
  <pre><code>static void CreateLabOrderInvoice(string html, string invoiceNumber)
      {
          try
          {
              string strHtml = null;
              MemoryStream memStream = new MemoryStream();
  
              strHtml = html;
  
              string strFileShortName = invoiceNumber + ".pdf";
              string strFileName = @"~\Invoices\" + strFileShortName;
              iTextSharp.text.Document docWorkingDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 40);
              StringReader srdDocToString = null;
  
              try
              {
                  PdfWriter pdfWrite = default(PdfWriter);
  
                  pdfWrite = PdfWriter.GetInstance(docWorkingDocument, new FileStream(strFileName, FileMode.Create));
                  srdDocToString = new StringReader(strHtml);
  
                  docWorkingDocument.Open();
  
                  Image logo = Image.GetInstance(@"~\images\Image_PPNLOGO.jpg");
                  logo.Alignment = Image.ALIGN_RIGHT;
  
                  docWorkingDocument.AddTitle("Lab Order Invoice");
                  docWorkingDocument.Add(logo);
  
                  XMLWorkerHelper.GetInstance().ParseXHtml(pdfWrite, docWorkingDocument, srdDocToString);
              }
              catch (System.Exception ex)
              {
                  throw ex;
              }
              finally
              {
                  if ((docWorkingDocument != null))
                  {
                      docWorkingDocument.Close();
                  }
                  if ((srdDocToString != null))
                  {
                      srdDocToString.Close();
                      srdDocToString.Dispose();
                  }
              }
          }
          catch (System.Exception ex)
          {
              throw ex;
          }
  
  
      }
  </code></pre>
  
  <p><strong>EDIT</strong>
  This is the Stack trace</p>
  
  <blockquote>
    <p>at ConsoleApplication1.Program.CreateLabOrderInvoice(String html,
    String invoiceNumber) in ~\Program.cs:line 416 at
    ConsoleApplication1.Program.&lt;>c__DisplayClass4.b__3(order
    currentOrder) in ~\Program.cs:line 70 at
    System.Threading.Tasks.Parallel.&lt;>c__DisplayClass2d<code>2.&lt;ForEachWorker&gt;b__23(Int32
    i) at
    System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClassf</code>1.b__c()</p>
  </blockquote>