【问题标题】:C# FORM copy program crashes because of too much RAM usageC# FORM 复制程序由于 RAM 使用过多而崩溃
【发布时间】:2021-12-16 10:37:54
【问题描述】:

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

当我复制时,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 对象。 Image 对象需要被释放,否则它们将保留在 RAM 中,直到垃圾收集器运行。如果你在一个紧密的循环中读取文件,GC 可能没有机会运行
  • Visual Studio 可能已经警告应该处理 img

标签: c# windows desktop-application .net-framework-4.8


【解决方案1】:

您需要在使用图像后对其进行处理,以便从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,                    
        }
    }

【讨论】:

  • using 语句可以作为单个命令使用,无需大括号。没有括号的代码更简洁。
  • @Exitare 使用语句的替代语法是在 C# 8.0 中引入的......不一定重要,但不是每个人都使用 C# 8.0。 docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
  • 谢谢。这解决了我的问题。 :)
  • 我知道。我只是想添加注释,让人们(和你)知道有一种更简单的方法来编写该代码。 @MartinMészáros 如果这回答了您的问题,请接受它:)
猜你喜欢
  • 2021-07-17
  • 2020-08-13
  • 2015-03-29
  • 2013-01-22
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
相关资源
最近更新 更多