Throwing the good doctor for a loop
Is it possible to drop into an endless loop yet keep the Windows message loop pumping? Ive always been told that this isnt possible, but hey, youre Dr. GUI perhaps by making appropriate (API or MFC) function calls from within the loop it is possible.
Lets assume I have a good reason (which I dont!) for wanting to do this. I realize that normally a timer loop (calling OnTimer()) would be used instead of the endless loop.
Steven D. Lacy
Kind of a loopy question, no? Note that this is actually a common problem: any operation, such as background printing, file I/O, or network I/O, that youd like to run in the background will need to keep the message pump going.
Well, there are a couple of ways to do this. Under Win32, the best way is to just spawn a new thread so that your infinite loop is run in a separate thread from the thread running the message pump. This thread should probably be a worker threadit shouldnt create any UI elements. And dont set the priority of this background thread too high or youll starve the system, okay? Multithreaded programming brings up a lot of tough issuesread about them in the Win32 SDK documentation. Note also that MFC supports multithreaded programming. Finally, note that the thread will be killed when your process exits.
Windows® 3.1x doesnt support multiple threads, so you cant spawn another thread to solve the problem. Therefore, you mustnt go into an infinite loop, or youll lock up the whole system. However, you can do background processing by writing a loop that, in addition to your background processing, frequently calls PeekMessage to check for messages that are waiting. When it gets messages, it must dispatch them. This non-preemptive multitasking will result in jerky, slow performance, but it will work. You can do this under Win32 as well, but I dont recommend it unless its just extraordinarily difficult to make your code safe for multiple threads.
And, in keeping with our Java theme: if youre programming in Java, rejoicemultithreaded support is built into the Java language. You still have to deal with the tough issues of more than one thread modifying data at the same time, but you at least get some solid support in both the language and run-time library for doing it right.