C# FORM 复制程序因 RAM 使用过多而崩溃

C# FORM copy program crashes because of too much RAM usage

我一直在尝试解决这个问题,但找不到解决方案。

当我复制 RAM 使用量超过 2gb 或更多时,我的笔记本电脑死机了。 我可以做什么来释放 RAM?

这个程序对水平和垂直照片进行排序,所以没什么大不了的,我知道代码不是最好的。

foreach (var srcPath in Directory.GetFiles(sourcePath))
        {
            
            string Name = Path.GetFileName(srcPath);
            //Gets the file's format (like png or jpeg)
            string ext = Path.GetExtension(srcPath);

            bool allowFile = false;

            //This line examines the correct file's format, if it's not correct it won't copy it.
            if (ext == ".png" || ext == ".jpeg" || ext == ".jpg" || ext == ".mp4" || ext == ".PNG" || ext == ".JPEG" || ext == ".JPG" || ext == ".MP4")
                allowFile = true;

            Image img = Image.FromFile(srcPath);

            int width = img.Width;
            int height = img.Height;
           

            if (allowFile)
            {
                if (height > width)
                {
                    File.Copy(srcPath, pathString + "\" + Name , true);
                }
                else
                {
                    File.Copy(srcPath, pathString2 + "\" + Name, true);
                }
    
                //Copy the file from sourcepath and place into mentioned target path,                    
            }
        }

您需要在使用后处理图像,以便从 Image.FromFile 调用中释放已用内存。

尝试将图像调用包装在 using:

using (Image img = Image.FromFile(srcPath)) 
    {
        int width = img.Width;
        int height = img.Height;

        if (allowFile)
        {
            if (height > width)
            {
                File.Copy(srcPath, pathString + "\" + Name , true);
            }
            else
            {
                File.Copy(srcPath, pathString2 + "\" + Name, true);
            }

            //Copy the file from sourcepath and place into mentioned target path,                    
        }
    }