views:

338

answers:

2

Hi, I'm using the code below to free up memory on some running programs because my own program needs large memory resources to run faster.

[DllImport("psapi.dll")]
public static extern bool EmptyWorkingSet(IntPtr hProcess);

public FreeMem(string programName){

      EmptyWorkingSet(Process.GetCurrentProcess().Handle);
      foreach(Process process in Process.GetProcesses(programName))
      {
            try
            {
                EmptyWorkingSet(process.Handle);
            }
            catch (Exception)
            {
                ...
            }
      } 
}

It seems to be working fine, I was able to bring down memory usage of some programs like explorer from 100,000 Kb down to 2,000 Kb. That's pretty good but is there a side effect on doing this? Some commercial software are also using this like Yamicsoft Vista/Xp manager and Firefox Optimizer to name a few so i'm thinking if this has no bad side effects or is there?

A: 

I suspect the side-effect will be performance of those other programs - the system will bring the pages swapped out by the call to EmptyWorkingSet() back in when the process needs them.

Messing with the system at such a low level is fraught with danger: in particular, Explorer page faults may slow the system down to the point where strange deadlocks start to rear their ugly heads. Best to leave this to Windows, in particular for other programs that you didn't write.

You may find it more efficient to understand why your own program needs so much memory. Is there a leak somewhere, perhaps?

Jeremy McGee
maybe you're right. I'll try to find a way to optimize my own program instead of optimizing the other programs and remove EmptyWorkingSet if its dangerous.
murasaki5
A: 

Personally, I've not deal with this. Seems kind of 'dangerous' :P

Anyway, some articles you might find helpful:
Performance Issues with EmptyWorkingSet
Memory management - forcing a process to free it's memory

o.k.w
what about SetProcessWorkingSetSize? i never used it before. What is the difference between the two?
murasaki5