【问题标题】:What is the optimal buffer size to increase efficiency of the application?提高应用程序效率的最佳缓冲区大小是多少?
【发布时间】:2018-02-16 10:01:30
【问题描述】:

我有一个应用程序,它读取文件并复制其内容并写入另一个文件。 我正在使用缓冲区读取文件并写入另一个文件。

文件较多时应用程序耗时过长。

我可以使用任何特定的最佳缓冲区大小值来提高应用程序的效率吗?

我已使用 256KB 作为最大缓冲区大小。

在 Parallel.ForEach 循环中调用以下上传方法。

下面是代码:

private bool Upload(string address, string uploadFile, string user, string password, string clientLogFile)
    {
        // Get the object used to communicate with the server. 
        FtpWebRequest request = null;
        try
        {
            request = (FtpWebRequest)WebRequest.Create(address);
            request.Credentials = new NetworkCredential(user, password);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.KeepAlive = false;
            request.Timeout = Convert.ToInt32(ConfigurationSettings.AppSettings["timeout"]);

            request.UsePassive = Convert.ToBoolean(ConfigurationSettings.AppSettings["ftpMode"]);
            // _fileBufferSize = 256kb
            byte[] buffer = new byte[_fileBufferSize];
            using (FileStream fs = new FileStream(uploadFile, FileMode.Open))
            {
                long dataLength = (long)fs.Length;
                long bytesRead = 0;
                int bytesDownloaded = 0;
                using (Stream requestStream = request.GetRequestStream())
                {
                    while (bytesRead < dataLength)
                    {
                        bytesDownloaded = fs.Read(buffer, 0, buffer.Length);
                        bytesRead = bytesRead + bytesDownloaded;
                        requestStream.Write(buffer, 0, bytesDownloaded);
                    }
                    requestStream.Close();
                }
            }
            return true;
        }
        catch (Exception ex)
        {
            // Catch exception
        }
        finally
        {
            request = null;
        }
        return false;
    }

欢迎所有建议。

【问题讨论】:

  • 您应该将您的问题发布到:codereview.stackexchange.com
  • 我的第一个想法是你做事是连续的……读,然后写,然后读,然后写。我会改变它,让它同时读取和写入。所以读取缓冲区 1。然后同时读取缓冲区 2 和写入缓冲区 1。然后在写入缓冲区 2 的同时读取缓冲区 3。
  • 该应用程序是否主要用于比当前最大缓冲区大小更小、大致相同或更大的文件?
  • 感谢您的建议。实际上,Upload() 方法是在 Parallel.ForEach 循环中调用的。所以,我认为它已经在做你提到的多任务处理。抱歉问题不完整,我会更新它。
  • @Mast,文件可以变化,大小可以小于或大于指定的缓冲区大小。

标签: c# file-io buffer filestream memorystream


【解决方案1】:

合并您的文件以上传到多个任务中运行,然后并行执行多个任务。

阅读this older guide from Microsoft 了解并行任务。其现代版本可能如下面的代码所示。

public void UploadAllFiles(IEnumerable<FileUploadParameters> files) {
    var tasks = new List<Task>();

    foreach (var file in files) {
        var task = Task.Run(() => {
            UploadFile(file);
        });

        tasks.Add(task);
    }

    Task.WaitAll(tasks.ToArray());
}

【讨论】:

  • 感谢您的建议。实际上,Upload() 方法是在 Parallel.ForEach 循环中调用的。所以,我认为它已经在做你提到的多任务处理。抱歉问题不完整,我会更新它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
  • 2013-11-02
  • 2011-06-06
相关资源
最近更新 更多