Parallel.ForEach处理并在ConcurrentDictionary中添加

时间:2015-02-10 05:18:06

标签: c# .net multithreading concurrency parallel-processing

我想将字节转换为pdf格式。因为我想加快使用并行/多线程功能的过程。

当MaxDegreeOfParallelism超过1时,问题是它是挂起还是分解。我猜内存已经损坏了。任何人都可以建议吗?

public ConcurrentDictionary<Int64, Byte[]> letterContentDictionary = new ConcurrentDictionary<Int64, Byte[]>();

private void ProcessFilesInParallel()
{
var files = _oldDbContext.LetterData.Where(x => x.ByteContent != null).Select(y => y).Take(100);
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = 4 }, file =>
{
    byte[] byteCompleteLetterPdf = null;
    byteCompleteLetterPdf = ConvertToPdfWithAspose(file.ByteContent);
    letterContentDictionary.TryAdd(file.LetterId, byteCompleteLetterPdf);
});
}

1 个答案:

答案 0 :(得分:0)

首先尝试在数组中缓冲DbContext结果,如下所示:

var files = _oldDbContext.LetterData.Where(x => x.ByteContent != null).Select(y => y).Take(100).ToArray();