How do you protect yourself from runaway memory consumption bringing down the PC?

一笑奈何 提交于 2019-12-03 12:18:11
dmb

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.

In Windows you can control the attributes of a process using Job Objects

I usually use Task Manager in that case to kill the process before the machine runs of memory. TaskMan runs pretty well even as the machine starts paging pretty badly. After that the machine will usually recover. Later versions of Windows (such as 7) generally have more survivability in these situations than earlier versions. Running without DWM (turning off Aero themes in Vista and 7) generally also gives more time to invoke taskman to monitor and potentially kill off runaway processes.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!