I'm trying to merge some PDF documents using a Parallel.For
loop so that I can create multiple documents at once. 99+% it works fine (and works perfectly when MaxDegreeOfParallelism = 1
) but I am getting an issue here when I merge multiple copies of the same PDF. transItem.DocumentList
would contain all the documents and their merge fields like this:
DocID Field Value
1 LastName Smith
2 Year 2015
2 Year 2016
2 Year 2017
Below is my code
var options = new ParallelOptions { MaxDegreeOfParallelism = -1 };
Parallel.ForEach(transItem.DocumentList, options, (docItem) =>
{
//Get list of merge field for this document
List<Document> fieldList = documentList.Where(x => x.document_id == docItem.document_id).ToList();
//Get the extension (if any) and make it part of the bar code
int extension = 0;
if (GlobeTax.GlobeTax.IsNumeric(docItem.extension))
extension = int.Parse(docItem.extension);
docItem.bar_code = "01" + extension.ToString("00") + transItem.TransactionID.ToString("00000000") + docItem.document_id.ToString("0000");
//Iterate through the field list and assign the values
foreach (Document docFieldItem in fieldList)
{
//Assign the value from the cobject containing the merge data.
GetFieldValue(docFieldItem, boData, docItem.extension, emailInstructionsSB.ToString());
docFieldItem.bar_code = docItem.bar_code;
}
pdfList[docItem.array_pos] = docManagerAPI.ProcessPDF(fieldList);
});
The result is that sometimes I get two document #2 with a year of 2016, none with 2015, and one with 2017. Sometimes the barcode value does not match the year on the document.
I'm pretty new to this and so may be making an obvious mistake. Does anything jump out at anyone?