【问题标题】:Parallel.ForEach processing and adding in ConcurrentDictionaryParallel.ForEach 处理并添加到 ConcurrentDictionary
【发布时间】:2023-03-26 19:05:01
【问题描述】:

我想将字节转换为 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);
});
}

【问题讨论】:

  • 当并行循环中断时你看到了什么错误?
  • 你确定你的方法ConvertToPdfWithAspose是线程安全的吗?

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


【解决方案1】:

尝试先将 DbContext 结果缓冲成一个数组,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多