我开发了适用于大型DataSet的.net 4.0 Windows服务。我知道DataSet并不是加载大量数据的最佳方法,与此同时,我在重新设计应用程序时,我想知道管理OutOfMemoryException的最佳方法,因为在第一次引发异常之后,它Windows服务启动的以下所有任务都会发生。我认为在内存不足异常发生后,它会为当前任务抛出该任务使用的内存,而GC无法清除该内存。
我的情况类似于
public partial class MyWinService : ServiceBase
{
DBService service;
IEnumerable<long> unfinishedRequests;
List<long> activeRequests;
protected override void OnStart(string[] args)
{
timer1.Elapsed += Timer_Tick;
timer1.Start();
activeRequests = new List<MyTask>();
}
private void Timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
MyTask task = GetNewScheduledAppointment();
If(task != null)
activeRequests.Add(task);
task = GetTaskToRun(activeRequests);
If(task != null)
RunTask(task );
}
private IRunNowToken RunTask(ServiceTask serviceTask)
{
ProcessRunner runner = CreateProcessRunner(serviceTask);
TaskFactory ts = new TaskFactory(serviceTask.TokenSource.Token);
ts.StartNew(() => { }).ContinueWith((Task tsk) =>
{
try
{
AddTask(serviceTask, tsk);
try
{
runner.Run();
}
finally
{
RemoveTask(serviceTask);
}
}
catch (Exception e)
{
HandleException(e);
}
finally
{
FinalizeRunAlarm(alarm);
}
}, serviceTask.TokenSource.Token);
return serviceTask.RunToken;
}
OutOfMemory执行由RunTask管理。如何修改它以确保将清除当前任务的内存?
谢谢
答案 0 :(得分:0)
Please note that fixing Memory leak is the correct way to fix this issue.
But as you said, meanwhile Please check if this works:
If you are running a 64 bit OS and RAM + VM > 4GB, goto Project > Properties > Build tab, untick the "Prefer 32-bit" checkbox and then try running the app.
If you get the same exception even after trying this, then I think you might have to start working on Re-Engineering your code.