我的程序使用linq查询从数据表中读取数据并将其写入本地文件。我将流和streamwriter包含在使用语句中,但我得到了许多系统内存异常。我是否应该在我的代码中调用数据表上的dispose方法?这是我能想到的唯一解决方案
我的代码:
public static async void getTrainingData(string symbol, string market)
{
decimal returnPct = 0, shortRating = 0, rsi = 0, mfi = 0, williamsR = 0, macd = 0, sma20 = 0, sma50 = 0, sma200 = 0;
string path = "training.csv";
List<Task> taskList = new List<Task>();
int count = 0;
try
{
using (Calculations calc = createCalcClass(symbol, market))
{
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Write, 4096, FileOptions.Asynchronous))
using (TextWriter writer = new StreamWriter(fs))
{
DateTime date;
var amexQuery = from c in calc.dailyAmexTable.AsEnumerable()
orderby c.Date descending
select c;
count = Convert.ToInt32(calc.dailyAmexAdapter.ScalarQuerySymbol(symbol));
for (int i = 0; i < count - 14; i++)
{
if (i != count - 15)
{
returnPct = calc.calculateReturnPercentage(amexQuery.ElementAtOrDefault(i + 1).AdjustedClose, amexQuery.ElementAtOrDefault(i).AdjustedClose);
date = amexQuery.ElementAtOrDefault(i + 1).Date;
if (returnPct >= 10)
{
calc.calculatePctGainsLosses(14, date);
shortRating = calculateRating(calc, ratingType.short_rating, date);
rsi = calc.calculateRSI(14, date);
mfi = calc.calculateMFI(14, date);
williamsR = calc.calculateWilliamsR(14, date);
macd = calc.calculateMACDDivergence(date);
sma20 = calc.calculateReturnPercentage(calc.calculateSMA(20, date),
calc.getSpecificValues(Calculations.valueType.Most_Recent_Close, 0, date));
sma50 = calc.calculateReturnPercentage(calc.calculateSMA(50, date),
calc.getSpecificValues(Calculations.valueType.Most_Recent_Close, 0, date));
sma200 = calc.calculateReturnPercentage(calc.calculateSMA(200, date),
calc.getSpecificValues(Calculations.valueType.Most_Recent_Close, 0, date));
Task write = TextWriter.Synchronized(writer).WriteLineAsync(returnPct + "," + symbol + "," + shortRating + "," +
rsi + "," + mfi + "," + williamsR + "," + macd + "," + sma20 + "," + sma50 + "," + sma200);
taskList.Add(write);
// add the necessary info to the training data file
// stock rating, pct change, rsi, mfi, williams r, macd, 20 day sma, 50 day sma, 200 day sma
}
}
}
await writer.FlushAsync();
}
// wait for all tasks to complete
Task.WaitAll(taskList.ToArray());
Console.WriteLine("Return percentages for " + symbol + " saved to training file.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
示例输出: