C# 对每个不一致的结果进行并行处理

C# 对每个不一致的结果进行并行处理,c#,parallel-processing,task-parallel-library,parallel.foreach,C#,Parallel Processing,Task Parallel Library,Parallel.foreach,我确保在并行循环中有并发收集。我希望循环结束时有35个唯一的文件路径。我看到重复文件路径的结果不一致。我错过了什么 ConcurrentBag<string> generatedPdfFilePaths = new ConcurrentBag<string>(); string generatedPdfPath = string.Empty; Parallel.ForEach(docxPaths, (docxpath)

我确保在并行循环中有并发收集。我希望循环结束时有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
    }                
}
ConcurrentBag GeneratedPdfilePath=新建
ConcurrentBag();
string generatedPdfPath=string.Empty;
Parallel.ForEach(docxpath,(docxpath)=>
{
generatedPdfPath=docxpath.Replace(“.docx”,“.pdf”);
if(ConvertDocxToPdf(docxpath,generatedPdfPath))
{ 
generatedPdfFilePaths.Add(generatedPdfPath);
}                    
});
//在此处使用GeneratedPdfilePath集合进行操作
公共bool ConvertDocxToPdf(字符串docxFilePath、字符串pdfFilePath)
{               
尝试
{
Aspose.Words.Document docx=新建
Aspose.Words.Document(docxFilePath);
docx.FontSettings=fontsetting;
docx.Save(pdfFilePath);
返回true;
}
捕获(例外情况除外)
{
//做事
}                
}

生成的PDFPATH
变量必须位于并行循环内。否则,所有线程(并行循环)都可以访问它。在循环内部,每个线程都会修改它,当线程尝试使用它时,“可能”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); 
    }                    
});
ConcurrentBag-generatedPdfFilePaths=new-ConcurrentBag();
Parallel.ForEach(docxpath,(docxpath)=>
{
string generatedPdfPath=string.Empty;
generatedPdfPath=docxpath.Replace(“.docx”,“.pdf”);
if(ConvertDocxToPdf(docxpath,generatedPdfPath))
{ 
generatedPdfFilePaths.Add(generatedPdfPath);
}                    
});

Move
string generatedPdfPath=string.Empty内部
并行。ForEach
循环体。现在,您无缘无故地从多个线程修改它。结果有什么不一致之处?@中间道歉-我通过在线美化器运行了代码,不喜欢结果,所以在Linqpad中重新格式化了它-我在Linqpad中粘贴时一定在剪贴板上有美化过的版本-真是罪过!