【发布时间】: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