Solution to growing memory usage problem
Created at 27 Aug 2015, 15:23
Solution to growing memory usage problem
27 Aug 2015, 15:23
To the cAlgo developers:
You can solve the growing memory usage problem by periodically forcing to free the memory.
Long running apps generally have this growing memory usage problem. On 32-bit systems it will eventually throw "System.OutOfMemoryException" and crash.
Usage:
In Program.cs file add these:
[STAThread] static void Main() { InitMemoryManager(TimeSpan.FromSeconds(30)); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } internal static void InitMemoryManager(TimeSpan dueTime) { var gate = new object(); var lastFreeTime = DateTime.Now.Ticks; Application.Idle += (sender, e) => { try { lock (gate) { if (DateTime.Now.Ticks - lastFreeTime <= dueTime.Ticks) { return; } MemoryManagerSingleton.Instance.Free(); lastFreeTime = DateTime.Now.Ticks; } } catch (Exception) { } }; MemoryManagerSingleton.Instance.Free(); }
And the Memory Manager is this:
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace MoneyBiz.Core { public sealed class MemoryManagerSingleton { private static volatile MemoryManagerSingleton _instance; private static readonly object _gate = new object(); private MemoryManagerSingleton() { } public static MemoryManagerSingleton Instance { get { if (_instance == null) { lock (_gate) { if (_instance == null) { _instance = new MemoryManagerSingleton(); } } } return _instance; } } [DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)] internal static extern bool SetProcessWorkingSetSize32(IntPtr pProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize); [DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)] internal static extern bool SetProcessWorkingSetSize64(IntPtr pProcess, long dwMinimumWorkingSetSize, long dwMaximumWorkingSetSize); public void Free() { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { return; } try { using (var process = Process.GetCurrentProcess()) { if (Environment.Is64BitProcess) { SetProcessWorkingSetSize64(process.Handle, -1, -1); } else { SetProcessWorkingSetSize32(process.Handle, -1, -1); } } } catch { } } } }
Good luck.
Replies
moneybiz
27 Aug 2015, 20:58
RE:
I created a robot which periodically frees the excess memory.
Check here: Memory Manager Bot
@moneybiz
moneybiz
27 Aug 2015, 18:13
RE:
Later today I'll post an indicator/robot which you can run and auto free the memory.
@moneybiz