C#Threading Parallel.ForEach和DirectoryInfo内存异常

时间:2012-03-30 13:17:19

标签: c# multithreading directoryinfo

我有一个非常简单的Parallel.ForEach,它调用下面的代码:

var maxDegree = new ParallelOptions{MaxDegreeOfParallelism = 5};
Parallel.ForEach(PList,maxDegree,fl =>
            {
                ProjectDirectoryProcessing pjp = new ProjectDirectoryProcessing();
                pjp.ProjectProcessor(fl);
                Console.ReadLine();
            }
        );

public class ProjectDirectoryProcessing
{

    public void ProjectProcessor(string rootDirectory)
    {
           DirectoryInfo Dinfo = new DirectoryInfo(rootDirectory);
            DirectoryInfo[] directories = Dinfo.GetDirectories("*.*", SearchOption.AllDirectories);
            FileInfo[] finfo = Dinfo.GetFiles("*.*", SearchOption.AllDirectories);
            foreach (FileInfo f in finfo)
            {
                FileSize = FileSize + f.Length;
            }
            FileCount = finfo.Length;
            DirectoryCount = directories.Length;
    }
}

问题是我的内存不足,我想到了Parallel.ForEach中的pjp.ProjectProcessor之后的GC.Collect(),但我不确定这是否会起作用。目录是非常大的,我不肯定清理那些将有助于这么多。处理这个问题的好方法是什么?

1 个答案:

答案 0 :(得分:0)

手动调用GC无济于事,因为在抛出OutOfMemoryException之前应自动调用GC。 一个简单的解决方案是将应用程序编译为x64。这是一个选择吗?