静态方法的内存超出范围异常

时间:2017-11-25 19:18:24

标签: c# .net visual-studio memory-management out-of-memory

我的静态方法比较了两个jpeg文件,我得到Memory Out of Range异常。

我能够使用探查器确定我的代码的哪一部分消耗的内存最多,但是,我无法释放内存,即使我尝试了GC.Collect()

public static bool IsDuplicate(string newFile, string pathDestination)
{
    string[] destinationFiles = Directory.GetFiles(pathDestination); // 1100 jpeg files.
    foreach (var file in destinationFiles)
    {
        if (CompareImageFiles(newFile, file))
            return true;
    }
    return false;
}

//1100 jpeg files (pathFile2) being compared with one jpeg file (pathFile1)
public static bool CompareImageFiles(string pathFile1, string pathFile2)
{
     // Memory consumption around 1 GB by ms
    MemoryStream ms = new MemoryStream();
     // Memory consumption around 2.7 GB by img1
    System.Drawing.Image img1 = System.Drawing.Image.FromFile(pathFile1);

     // Memory consumption around 3 GB by img2
    System.Drawing.Image img2 = System.Drawing.Image.FromFile(pathFile2);
    if (!(img1.Height == img2.Height && img1.Width == img2.Width))
    {
        return false;   // Dimensions mismatch
    }
    else
    {
        img1.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        string image1 = Convert.ToBase64String(ms.ToArray());
        img2.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        string image2 = Convert.ToBase64String(ms.ToArray());
        if (image1.Equals(image2))
        {
             // This didn't work
            //ms = null; img1 = null; img2 = null; image1 = null; image2 = null;
            return true;
        }
        else
        {
             // This didn't work
            //ms = null; img1 = null; img2 = null; image1 = null; image2 = null;
            return false;
        }
    }
}

一点背景:是的,我确实理解这不是比较图像文件的完美方法(我第一次尝试处理图像文件)。我已经启动了此任务的新优化版本(正在进行中)。

然而,由于这个解决方案在过去几个月开始工作,并且最近开始破坏。所以,在我归档这种方法之前,至少我想解决这个问题,这给了我很好的学习。

1 个答案:

答案 0 :(得分:4)

您应该处理Image个实例和内存流,方法是将它们放在using语句中,或者在完成后再手动调用Dispose()

public static bool CompareImageFiles(string pathFile1, string pathFile2)
{
    using (var ms = new MemoryStream())
    using (var img1 = System.Drawing.Image.FromFile(pathFile1))
    using (var img2 = System.Drawing.Image.FromFile(pathFile2))
    {
        // Rest of your code...
    }
}