繁体   English   中英

在 ASP.NET Core 7 中编写响应时使用 Thread.Sleep()

[英]Use Thread.Sleep() while writing response in ASP.NET Core 7

有没有办法在作为响应写入的字节之间进行延迟,以限制下载速度? 我的意思是,我想通过写入字节作为响应来返回一个大文件。 但我想限制它的速度,所以它会提高服务器性能。

我有这段代码可以让我将文件发送给客户端。 它运作良好。 但是当我添加睡眠方法时,浏览器甚至不会开始下载。

public IActionResult DownloadBigFile ()
{
    string filePath = "C:\\Users\\Matin\\source\\repos\\WebApplication1\\WebApplication1\\wwwroot\\Music.zip";
    var fileName = Path.GetFileName(filePath); // test document.xlsx

    int bufferSize = 1024 ; // This is the cache size for ASP.NET Core to read the downloaded file in a loop, here we set it to 1024 bytes, that is to say, ASP.NET Core will read 1024 bytes from the downloaded file every time The content is stored in the server memory, and then sent to the client browser, which avoids loading the entire downloaded file into the server memory at one time, causing the server to crash. 

    Response.ContentType = " application/zip "; // Because we The download is an Excel file, so set the ContentType to application/vnd.ms-excel

    string utf8EncodingFileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
    Response.Headers.Add ("Content-Disposition", "attachment;filename=" + utf8EncodingFileName);

    // Use FileStream to start looping to read the content of the file to be downloaded 
    using (FileStream fs = new FileStream (filePath, FileMode.Open, FileAccess.Read))
    {
        using (Response.Body) // Calling Response.Body.Dispose() will not close the connection from the client browser to the ASP.NET Core server, and you can continue to write data to Response.Body after that 
        {
            long contentLength = fs .Length; // Get the size of the downloaded file 
            Response.ContentLength = contentLength; // Set the size of the downloaded file in the Response Header, so that the client browser can correctly display the download progress

            byte [] buffer;
            long hasRead = 0 ; // The variable hasRead is used to record how many bytes of data have been sent to the client browser

            // If hasRead is less than contentLength, it means that the downloaded file has not been read yet, continue to read the content of the downloaded file in a loop, and send it to the client browser 
            while (hasRead < contentLength)
            {
                // HttpContext.RequestAborted.IsCancellationRequested can be used to detect the connection status between the client browser and the ASP.NET Core server. If HttpContext.RequestAborted.IsCancellationRequested returns true, it means that the client browser has interrupted the connection 
                if (HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // If the client browser interrupts the connection to the ASP.NET Core server, it should break immediately, cancel the reading and sending of the downloaded file, and avoid the server consuming resource 
                    break;
                }

                if (hasRead >= 81920)
                {
                    break;
                }

                buffer = new byte[bufferSize];

                int currentRead = fs.Read(buffer, 0 , bufferSize); // Read bufferSize (1024 bytes) content from the downloaded file into the server memory 

                Response.Body.Write (buffer, 0, currentRead); // Send the read content data to the client browser 
                Response.Body.Flush (); // Note that after each Write, the Flush method should be called in time to release the server memory space 
                hasRead += currentRead; // The update has been sent to the client end browser bytes 
                
                Thread.Sleep (10);
            }
        }
    }

    return new EmptyResult ();
}

我过去曾尝试做类似的事情。 这个线程帮助了我: How to limit speed downloading file in asp.net mvc 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM