Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

delphi - SetProcessWorkingSetSize - What's the catch?

I found an article on About.com that tells you how you can manage your apps memory.

Here is the code:

procedure TrimAppMemorySize;
var
  MainHandle : THandle;
begin
  try
    MainHandle := OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessID) ;
    SetProcessWorkingSetSize(MainHandle, $FFFFFFFF, $FFFFFFFF) ;
    CloseHandle(MainHandle) ;
    Log('Trimmed Memory Successfull!');
  except
    Log('Failed to trim Memory!');
  end;
  Application.ProcessMessages;
end;

I tried it out, works perfectly - Even when my app is doing something, and I fire buttonclicks, etc, it still does its thing, and it works like a charm. I look at my apps Memory usage in the Resource Monitor, and as far as I can see, its all good.

So.. Whats the catch? We all deal with memory issues, but is the solution really that simple? Can anyone tell me if doing this every 60 seconds is a bad thing?

I will reboot and try to run my program, and post a screenshot of my Resource Monitor.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, it's a bad thing. You're telling the OS that you know more about memory management than it does, which probably isn't true. You're telling to to page all your inactive memory to disk. It obeys. The moment you touch any of that memory again, the OS has to page it back into RAM. You're forcing disk I/O that you don't actually know you need.

If the OS needs more free RAM, it can figure out which memory hasn't been used lately and page it out. That might be from your program, or it might be from some other program. But if the OS doesn't need more free RAM, then you've just forced a bunch of disk I/O that nobody asked for.

If you have memory that you know you don't need anymore, free it. Don't just page it to disk. If you have memory that the OS thinks you don't need, it will page it for you automatically as the need arises.

Also, it's usually unwise to call Application.ProcessMessages unless you know there are messages that your main thread needs to process that it wouldn't otherwise process by itself. The application automatically processes messages when there's nothing else to do, so if you have nothing to do, just let the application run itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...