How do you protect yourself from runaway memory consumption bringing down the PC?
You could keep a command prompt open whenever you run a risky app. Then, if it starts to get out of control, you don't have to wait for Task Manager to load, just use:
taskkill /F /FI "MEMUSAGE ge 2000000"
This will (in theory) force kill anything using more than 2GB of memory.
Use taskkill /?
to get the full list of options it takes.
EDIT: Even better, run the command as a scheduled task every few minutes. Any process that starts to blow up will get zapped automatically.
There's something you can do: limit the working set size of your process. Paste this into your Main() method:
#if DEBUG Process.GetCurrentProcess().MaxWorkingSet = new IntPtr(256 * 1024 * 1024);#endif
That limits the amount of RAM your process can claim, preventing other processes from getting swapped out completely.
Other things you can do:
- Add more RAM, no reason to not have at least 3 Gigabytes these days.
- Defrag your paging file. That requires defragging the disk first, then defrag the paging file with, say, SysInternals' pagedefrag utility.
Especially the latter maintenance task is important on old machines. A fragged paging file can dramatically worsen swapping behavior. Common on XP machines that never were defragged before and have a smallish disk that was allowed to fill up. The paging file fragmentation causes a lot of disk head seeks, badly affecting the odds that another process can swap itself back into RAM in a reasonable amount of time.
The obvious answer would be to run your program inside of a virtual machine until it's tested to the point that you're reasonably certain such things won't happen.
If you don't like that amount of overhead, there is a bit of middle ground: you could run that process inside a job object with a limit set on the memory used for that job object.