为静态方法获取内存超出范围异常

Getting Memory Out of Range exception for static method

我比较两个 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;
        }
    }
}

一点背景知识: 是的,我知道这不是比较图像文件的完美方法(我第一次尝试处理图像文件)。我已经开始了这个任务的新优化版本(进行中)。

但是,由于此解决方案在过去几个月内一直有效,但最近开始出现故障。所以,在我将这种方法归档之前,至少我想解决这个问题,这让我得到了很好的学习。

您应该处理 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...
    }
}