晚上好,
我正在尝试提高从c#.net应用程序中的web api获取文件的性能。 c#应用程序使用高CPU使用率加上dosnt似乎非常快,本地1GB文件大约需要40秒。这台机器正在运行高速NVMe SSD,所以我不相信它的硬件。
请注意,以下内容正在同一台机器上进行测试。我们的生产速度很慢,但可能是由于网络或其他问题。因此,我只想检查代码库中是否有效率。
用于下载的WPF应用程序代码是:
public async Task Test()
{
AppModel.StartTime = DateTime.Now;
var sourceFile = HttpUtility.UrlEncode("e820e6d8-4544-4f17-84e3-61e90ccd7e24.zip");
var url = $"api/UploadDownload";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(AppModel.BaseUrl);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", AppModel.Token);
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
using (var streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
var fileToWriteTo = Path.GetTempFileName();
using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
AppModel.EndTime = DateTime.Now;
var difference = AppModel.EndTime - AppModel.StartTime;
var totalSeconds = (int) Math.Round( difference.TotalSeconds);
AppModel.TotalSeconds = totalSeconds;
var fileInfo = new FileInfo(fileToWriteTo);
AppModel.TotalMbDownload = ConvertBytesToMegabytes(fileInfo.Length);
var averageSpeed = AppModel.TotalMbDownload / totalSeconds;
AppModel.Speed = averageSpeed;
File.Delete(fileToWriteTo);
}
}
}
api代码如下:
[HttpGet]
[System.Web.Http.Authorize]
public HttpResponseMessage GetSingleFile()
{
var dh = new DirectoryHelper();
var sourceDir = "";
// var filepath = ConfigurationManager.AppSettings["UploadDownloadLocation"] + "\\" + fileName;
HttpResponseMessage result = null;
var filepath = sourceDir + fileName;
var localFilePath = filepath;
if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
// Serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.zip"
};
}
return result;
}
任何建议都会非常有用,不确定是否有更好的方法可以提高性能。
由于