The Render Loop Revisited

Wow. I wouldn’t have thought that my blog on the render loop and doevents would spark as much discussion as it did. Invariably everyone wanted to know what i thought the ‘best’ way to do this was.

Actually, the answer is (naturally) ‘It Depends’. It wasn’t actually an oversight on my part to leave out a recommendation at the end of the post, it was done intentionally. I had hoped to spark peoples interest in learning the cost of the methods they were calling, and pointing out a common scenario where the method had side effects that many people weren’t aware of.

However, since I’ve been asked quite a few times on alternatives, I feel obligated to provide some. =)

Here are some alternatives, in no particular order.

  • Set your form to have all drawing occur in WmPaint, and do your rendering there. Before the end of the OnPaint method, make sure you do a this.Invalidate(); This will cause the OnPaint method to be fired again immediately.
  • P/Invoke into the Win32 API and call PeekMessage/TranslateMessage/DispatchMessage. (Doevents actually does something similar, but you can do this without the extra allocations).
  • Write your own forms class that is a small wrapper around CreateWindowEx, and give yourself complete control over the message loop.
  • Decide that the DoEvents method works fine for you and stick with it.

Each of these obviously have benefits and disadvantages over the others. Pick the one that best suits your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *