如何降低Azure Web应用临时文件的利用率?

问题描述 投票:0回答:1

我有一个用 ASP.Net MVC 5 开发的 Web 应用程序,托管在 Azure 中。我使用的是共享应用服务,而不是虚拟机。最近Azure开始显示警告,我需要减少我的应用程序对工人临时文件的使用。

临时文件的使用率

重启应用后,问题已经消失了。看来,临时应用是通过做重启来清除的。

如何检测和防止临时文件使用量的意外增长。我不知道是什么产生了20GB的临时文件。我应该寻找什么来减少应用程序对临时文件的使用?我在代码中并没有明确的在临时文件中存储任何东西,数据是存储在数据库中的,所以不知道该找什么?

为了使临时文件的使用量保持在健康的状态,防止任何意外的增长,应该遵循哪些最佳实践?

注:在我的Web App中,我有多个虚拟路径,物理路径相同。

虛擬路徑

try
{
if (file != null && file.ContentLength > 0)
{
    var fileName = uniqefilename;

    CloudStorageAccount storageAccount = AzureBlobStorageModel.GetConnectionString();

    if (storageAccount != null)
    {
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        string containerName = "storagecontainer";

        CloudBlobContainer container = blobClient.GetContainerReference(containerName);
        bool isContainerCreated = container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);                                

        CloudBlobDirectory folder = container.GetDirectoryReference("employee");

        CloudBlockBlob blockBlob = folder.GetBlockBlobReference(fileName);

        UploadDirectory = String.Format("~/upload/{0}/", "blobfloder");
        physicalPath = HttpContext.Server.MapPath(UploadDirectory + fileName);
        file.SaveAs(physicalPath);
        isValid = IsFileValid(ext, physicalPath);
        if (isValid)
        {
            using (var fileStream = System.IO.File.OpenRead(physicalPath))
            {                                        
                blockBlob.Properties.ContentType = file.ContentType;
                blockBlob.UploadFromFile(physicalPath);
                if (blockBlob.Properties.Length >= 0)
                {
                    docURL = blockBlob.SnapshotQualifiedUri.ToString();
                    IsExternalStorage = true;
                    System.Threading.Tasks.Task T = new System.Threading.Tasks.Task(() => deletefile(physicalPath));
                    T.Start();
                }
            }
        }
    }
 }
}
catch (Exception ex)
{

}


//Delete File 
public void deletefile(string filepath)
{
  try
  {
    if (!string.IsNullOrWhiteSpace(filepath))
    {
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        System.IO.File.Delete(filepath);
    }
  }
  catch(Exception e) { }
 }
azure asp.net-mvc-5 azure-web-sites temporary-files
1个回答
0
投票

你的问题可能是由使用临时文件处理上传或下载引起的。解决的办法是使用内存流而不是filestream来处理文件,或者在处理完毕后删除临时文件。本次SO交流有一些相关建议。Azure Web App临时文件清理责任

鉴于你的更新,看起来你的文件上传代码让临时文件在第39行中累积,因为你没有在退出之前等待你删除文件的异步调用完成。我假设这个代码块被藏在一个MVC控制器动作里面,这意味着,一旦代码块完成,它将放弃未等待的异步动作,给你留下一个未删除的临时文件。

考虑更新你的代码到 await 你的 Task 动作。另外,你可能需要更新到 Task.Run. 例如:

var t = await Task.Run(async delegate
{
    //perform your deletion in here
    return some-value-if-you-want;
});
© www.soinside.com 2019 - 2024. All rights reserved.