byte []的空闲内存

问题描述 投票:2回答:3

我目前正在努力解决c#中的内存使用问题。

我目前正在处理的工具能够上传和下载文件。为此,它使用字节数组作为文件内容的缓冲区。在上传或下载操作之后,我可以处理WebResponse和Stream(+ Reader / Writer)对象,但是字节数组永远存在于内存中。它超出范围我甚至'空'它,所以我猜垃圾收集永远不会运行。

在搜索时,我发现很多文章建议永远不要手动运行GC,但是有一个简约的后台应用程序,不断占用100甚至1000 MB的RAM(不断增加你使用它的时间越来越长)是不错的。

那么,如果不建议使用GC,还能在这种情况下做些什么?

编辑3 /解决方案:我最终使用了一个16kb字节缓冲区,它填充了来自文件i / o的数据。之后,将缓冲区内容写入RequestStream,并采取进一步的操作(更新进度条等)。

编辑2:这似乎与LOH有关。我将在周五进行测试并在此处记录结果。

编辑:这是代码,也许我错过了参考?

    internal void ThreadRun(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        UploadItem current = Upload.GetCurrent();

        if (current != null)
        {
            string localFilePath = current.src;
            string fileName = Path.GetFileName(localFilePath);
            elapsed = 0;
            progress = 0;

            try
            {
                string keyString = Util.GetRandomString(8);

                worker.ReportProgress(0, new UploadState(0, 0, 0));

                FtpWebRequest req0 = Util.CreateFtpsRequest("ftp://" + m.textBox1.Text + "/" + keyString, m.textBox2.Text, m.textBox3.Text, WebRequestMethods.Ftp.MakeDirectory);

                req0.GetResponse();

                FtpWebRequest req1 = Util.CreateFtpsRequest("ftp://" + m.textBox1.Text + "/" + keyString + "/" + fileName, m.textBox2.Text, m.textBox3.Text, WebRequestMethods.Ftp.UploadFile);

                worker.ReportProgress(0, new UploadState(1, 0, 0));

                byte[] contents = File.ReadAllBytes(localFilePath);

                worker.ReportProgress(0, new UploadState(2, 0, 0));

                req1.ContentLength = contents.Length;

                Stream reqStream = req1.GetRequestStream();

                Stopwatch timer = new Stopwatch();
                timer.Start();

                if (contents.Length > 100000)
                {
                    int hundredth = contents.Length / 100;

                    for (int i = 0; i < 100; i++)
                    {
                        worker.ReportProgress(i, new UploadState(3, i * hundredth, timer.ElapsedMilliseconds));
                        reqStream.Write(contents, i * hundredth, i < 99 ? hundredth : contents.Length - (99 * hundredth));
                    }
                }
                else
                {
                    reqStream.Write(contents, 0, contents.Length);
                    worker.ReportProgress(99, new UploadState(3, contents.Length, timer.ElapsedMilliseconds));
                }

                int contSize = contents.Length;
                contents = null;

                reqStream.Close();

                FtpWebResponse resp = (FtpWebResponse)req1.GetResponse();

                reqStream.Dispose();

                if (resp.StatusCode == FtpStatusCode.ClosingData)
                {
                    FtpWebRequest req2 = Util.CreateFtpsRequest("ftp://" + m.textBox1.Text + "/storedfiles.sfl", m.textBox2.Text, m.textBox3.Text, WebRequestMethods.Ftp.AppendFile);

                    DateTime now = DateTime.Now;

                    byte[] data = Encoding.Unicode.GetBytes(keyString + "/" + fileName + "/" + Util.BytesToText(contSize) + "/" + now.Day + "-" + now.Month + "-" + now.Year + " " + now.Hour + ":" + (now.Minute < 10 ? "0" : "") + now.Minute + "\n");

                    req2.ContentLength = data.Length;

                    Stream stream2 = req2.GetRequestStream();

                    stream2.Write(data, 0, data.Length);
                    stream2.Close();

                    data = null;

                    req2.GetResponse().Dispose();
                    stream2.Dispose();

                    worker.ReportProgress(100, new UploadState(4, 0, 0));
                    e.Result = new UploadResult("Upload successful!", "A link to your file has been copied to the clipboard.", 5000, ("http://" + m.textBox1.Text + "/u/" + m.textBox2.Text + "/" + keyString + "/" + fileName).Replace(" ", "%20"));
                }
                else
                {
                    e.Result = new UploadResult("Error", "An unknown error occurred: " + resp.StatusCode, 5000, "");
                }
            }
            catch (Exception ex)
            {
                e.Result = new UploadResult("Connection failed", "Cannot connect. Maybe your credentials are wrong, your account has been suspended or the server is offline.", 5000, "");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
c# memory-management
3个回答
10
投票

核心问题是你从一个大块的文件中读取。如果文件非常大(准确地说大于85,000个字节),那么您的字节数组将存储在LOH(大对象堆)中。

如果你读到'大对象堆'(如果你谷歌它有很多关于这个主题的信息),你会发现它往往比GC其他堆区域收集的频率低很多,而不是提到默认情况下它不会压缩内存,这会导致碎片并最终导致“内存不足”异常。

在您的情况下,您需要做的就是以较小的块读取和写入字节,使用固定大小的字节数组缓冲区(例如:4096),而不是尝试一次读取所有文件。换句话说,您在缓冲区中读取了几个字节,然后将它们写出来。然后你又读了几个相同的缓冲区,然后再把它写出来。并且你继续这样做,直到你读完整个文件。

请参阅:Here,了解如何以较小的块读取文件,而不是使用

File.ReadAllBytes(localFilePath);

通过这样做,您将始终在任何给定时间处理合理数量的字节,以便在完成后GC不会及时收集任何问题。


6
投票

只需编写更智能的代码。根本不需要将整个文件加载到byte []中以将其上载到FTP服务器。您只需要一个FileStream。使用其CopyTo()方法从FileStream复制到从GetRequestStream()获得的NetworkStream。

如果你想显示进度然后你必须自己复制,一个4096字节的缓冲区可以完成工作。大致:

using (var fs = File.OpenRead(localFilePath)) {
    byte[] buffer = new byte[4096];
    int total = 0;
    worker.ReportProgress(0);
    for(;;) {
       int read = fs.Read(buffer, 0, buffer.Length);
       if (read == 0) break;
       reqStream.Write(buffer, 0, read);
       total += read;
       worker.ReportProgress(total * 100 / fs.Length);
    }
 }

未经测试,应该在球场。


3
投票

垃圾收集对于大型对象是不同的 - 并且仅适用于.NET Framework 4.5.1及更高版本。

此代码将释放大对象堆:

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect(); 

另见:https://msdn.microsoft.com/en-us/library/system.runtime.gcsettings.largeobjectheapcompactionmode(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

© www.soinside.com 2019 - 2024. All rights reserved.