并行处理每个不一致的结果

Parallel for each inconsistent results

我确保我在并行内有并发收集 loop.I 我期望在循环结束时有 35 个唯一的文件路径。我看到重复文件路径的结果不一致。我在这里错过了什么?

ConcurrentBag<string> generatedPdfFilePaths = new 
    ConcurrentBag<string>();                   
string generatedPdfPath = string.Empty;   
Parallel.ForEach(docxPaths, (docxpath) =>                    
{
    generatedPdfPath = docxpath.Replace(".docx", ".pdf");
    if (ConvertDocxToPdf(docxpath, generatedPdfPath))
    { 
        generatedPdfFilePaths.Add(generatedPdfPath); 
    }                    
});

// do stuff with generatedPdfFilePaths collection here
public bool ConvertDocxToPdf(string docxFilePath, string pdfFilePath)
{               
    try
    {
        Aspose.Words.Document docx = new
            Aspose.Words.Document(docxFilePath);
        docx.FontSettings = fontsetting;
        docx.Save(pdfFilePath);                   
        return true;
    }
    catch (Exception ex)
    {
        //do stuff
    }                
}

generatedPdfPath变量必须在并行循环内。否则它可以被所有线程访问(并行循环)。在循环内部,每个线程都会修改它,当线程尝试使用它时,'probably' generatedPdfPath 值会被另一个线程更改。这种情况导致竞争条件。因此,每次执行都会给出不同的结果。

如果将此行 string generatedPdfPath = string.Empty; 移动到循环中,问题必须得到解决。

ConcurrentBag<string> generatedPdfFilePaths = new ConcurrentBag<string>();                   

Parallel.ForEach(docxPaths, (docxpath) =>                    
{
    string generatedPdfPath = string.Empty;   
    generatedPdfPath = docxpath.Replace(".docx", ".pdf");
    if (ConvertDocxToPdf(docxpath, generatedPdfPath))
    { 
        generatedPdfFilePaths.Add(generatedPdfPath); 
    }                    
});