我的代码遇到了一些奇怪的行为,我用这些行为将文件流式传输到我的客户。我有一个用作文件存储的 mssql 服务器,其中包含通过 UNC 路径访问的文件。
在我的网络服务器上,我运行了一些 .net 代码,用于将文件(在本例中为图片和缩略图)流式传输到我的客户。
我的代码有效,但我在初始文件请求时遇到了约 12 秒的持续延迟。当我发出初始请求时,服务器唤醒并突然变得响应,只是在一段时间后回退到相同的行为。
起初我以为这是我的代码,但从我在服务器活动日志中看到的内容来看,没有资源密集型代码正在运行。我的理论是,在每次调用服务器时,必须首先安装路径,这就是导致延迟的原因。然后它将在一段时间后卸载,并且必须重新安装。
作为参考,我发布了我的代码(也许我只是看不到问题):
public async static Task StreamFileAsync(HttpContext context, FileInfo fileInfo)
{
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 512 * 1024; // 512KB
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// Clear the current response content/headers
context.Response.Clear();
context.Response.ClearHeaders();
//Indicate the type of data being sent
context.Response.ContentType = FileTools.GetMimeType(fileInfo.Extension);
//Name the file
context.Response.AddHeader("Content-Disposition", "filename=\"" + fileInfo.Name + "\"");
context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
// Open the file
using (var stream = fileInfo.OpenRead())
{
// The number of bytes read
int length;
do
{
// Verify that the client is connected
if (context.Response.IsClientConnected)
{
// Read data into the buffer
length = await stream.ReadAsync(buffer, 0, bytesToRead);
// and write it out to the response's output stream
await context.Response.OutputStream.WriteAsync(buffer, 0, length);
try
{
// Flush the data
context.Response.Flush();
}
catch (HttpException)
{
// Cancel the download if a HttpException happens
// (ie. the client has disconnected by we tried to send some data)
length = -1;
}
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// Cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
// Tell the response not to send any more content to the client
context.Response.SuppressContent = true;
// Tell the application to skip to the EndRequest event in the HTTP pipeline
context.ApplicationInstance.CompleteRequest();
}
如果有人能对这个问题有所了解,我将不胜感激!