【问题标题】:Application throws OutofMemoryException应用程序抛出 OutofMemoryException
【发布时间】:2018-07-26 20:46:51
【问题描述】:

各位程序员,大家好, 当前在我们的一个客户系统中运行的应用程序面临 OutofMemoryException 问题和应用程序崩溃。这个问题可能会在一两周内发生一次。使用 c# 开发的应用程序用于生产线。该机器几乎每 20 秒生成 28 个不同的 CSV 文件。该应用程序用于查找这些 CSV 文件并存档文件。因此应用程序每秒对数据库表(它是一个数据量很大的表)进行查询和更新/选择。我已经阅读了其他程序员关于这个问题的问题和答案,并相应地分析了我的代码,但由于缺乏经验,我可以在我的代码中找到内存泄漏。我想在这里分享一些我认为可能发生内存泄漏的代码部分。如果您能分享您的 cmets 或想法,我们将不胜感激。

代码

public void execute() //This is called every second 
 { 
    if (!this.busyBit) 
    {
        this.busyBit = true;
        CallAsyncFunction();
    }
  }
 protected async virtual void CallAsyncFunction()
 {
     await Task.Factory.StartNew(this.FileOperations); //is this correctly done?
 }
 protected virtual void FileOperations()
 {

   ////Searches for a new csv file
    if (!this. SearchTimestampInsideFileWithOddCounter())
    {
      //return error
    }

    if (!this.ArchiveFile())
    {
      //Archive the file
    }
      this.busyBit = false;
  }
 private bool SearchTimestampInsideFileWithOddCounter()
 {
     var directory = new DirectoryInfo(this.fileSearchPath);
    //Can the below code be a reason? because when I increased 
  //'numberOfFiles' to a huge number, the exception occured more frequently.
     FileInfo[] files = directory.EnumerateFiles().Where(f => 
     f.Extension.Equals(".csv", StringComparison.InvariantCultureIgnoreCase) 
    && f.Attributes != FileAttributes.Archive)                                       
   .OrderByDescending(fi => 
    fi.LastWriteTime).Take(this.numberOfFiles).ToArray();
   foreach (var file in files)
   {
         //Search for the required files from the list
         return true;

   }
   catch (Exception ex)
   {

   }
        return false;
 }

【问题讨论】:

  • 不要试图猜测内存泄漏的源头(在您显示的代码中没有任何内容)。使用分析器并找出

标签: c# sql out-of-memory task fileinfo


【解决方案1】:

我想答案可能在

应用程序每秒对数据库表(它是一个数据量很大的表)进行查询和更新/选择。

应用程序是一直在运行,还是每隔 n 秒运行一次?如果它是一个始终在线的应用程序,那么 如果 数据库对象没有正确处理,内存占用量将在每个周期增长。

【讨论】:

  • 谢谢@tymtam!该应用程序一直在运行。实际上,我将数据库类的对象创建为私有成员,并且该类包含连接 ID、连接字符串、ExecuteReader() 等成员。那么数据库对象是指它们吗?
猜你喜欢
  • 2015-02-28
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
  • 2013-03-08
  • 2016-04-01
  • 2013-07-17
相关资源
最近更新 更多