我无法找到由C#WPF应用程序中的函数引起的内存泄漏的特定来源,该函数通过DataContext将数据在一组循环中写入SQL DB。我怀疑有些物品没有妥善处理,但我找不到它们。
我尝试在函数中实例化一个新的DataContext来处理所有数据库交互,并在函数末尾显式调用GC.Collect()。这会减慢内存泄漏,但不会消除它。我尝试过使用ANTS Memory Profiler,但它的快照实例列表&分类程序不列出对象名称,只显示逐渐增加的通用对象实例数。
编辑(和编辑#2):怀疑内存泄漏的罪魁祸首(编辑2:带被调用的函数) -
private void Eq_Get_HistoricalData(String filename, String Symbol)
{
List<String[]> fileContents = new List<String[]>();
List<DailyDataRowObj> data = new List<DailyDataRowObj>();
DBHandler_Equities DBHE = new DBHandler_Equities();
ExternalDataHandler EDHP = new ExternalDataHandler();
Utilities UT = new Utilities();
if (File.Exists(filename)) {
fileContents = EDHP.parseCSV(filename);
for (int i = 1; i < fileContents.Count; i++) {
data.Add(Convert_HistoricalCSVRowToDDRO(fileContents[i], Symbol));
DBHE.Insert_DailyData_1Day(data[i - 1].Date, Symbol);
}
DBHE.Update_DailyData(data);
} else {
Console.WriteLine("Eq_Get_HistoricalData: " + Symbol + " file does not exist");
}
if (GlobalVar.GlobalDebugDisplay > DebugDisplayLevel.BaseLevel) {
UT.WriteToTextFile("C:/debug.txt", "Data pull for " + Symbol + " ended: " + DateTime.Now.ToShortTimeString());
}
}
/////////////////////////////////////////////////////////////////////
// Separate code snippet, from DBHandler_Equities class definition //
public void Update_DailyData(List<DailyDataRowObj> DailyDataInput)
{
int numRows = DailyDataInput.Count;
int r = 0;
using (EquitiesDataContext db = new EquitiesDataContext()) {
try {
for (r = 0; r < numRows; r++) { // loop through PNodeIDs
var currRow = // query LMP components for 1 region, 1 hour
(from c in db.DailyDatas
where c.Symbol == DailyDataInput[r].Symbol
&& c.Date == DailyDataInput[r].Date
select c).First();
if (DailyDataInput[r].Price_Close > 0)
currRow.Price_Close = DailyDataInput[r].Price_Close;
if (DailyDataInput[r].Price_High > 0)
currRow.Price_High = DailyDataInput[r].Price_High;
if (DailyDataInput[r].Price_Low > 0)
currRow.Price_Low = DailyDataInput[r].Price_Low;
if (DailyDataInput[r].Price_Open > 0)
currRow.Price_Open = DailyDataInput[r].Price_Open;
if (DailyDataInput[r].Volume > 0)
currRow.Volume = DailyDataInput[r].Volume;
if (DailyDataInput[r].Return_Close != 0)
currRow.Return_Close = DailyDataInput[r].Return_Close;
if (DailyDataInput[r].Return_High != 0)
currRow.Return_High = DailyDataInput[r].Return_High;
if (DailyDataInput[r].Return_Low != 0)
currRow.Return_Low = DailyDataInput[r].Return_Low;
}
} catch (Exception e) {
Console.WriteLine("Error: Update_DailyData - DT: " + Convert.ToString(DailyDataInput[r].Date)
+ ", Symbol: " + r.ToString() + " - " + e.Message);
}
try {
db.SubmitChanges();
} catch (Exception) {
Console.WriteLine("Error: Update_DailyData - DT: " + Convert.ToString(DailyDataInput[r].Date)
+ ", Symbol: " + DailyDataInput[r].Symbol.ToString() + " - db.submitChanges");
}
db.Dispose();
}
GC.Collect();
}
注意:DBHandler_Equities.Update_DailyData包含DataContext,它在结尾处显式收集。