Quantcast
Channel: CodeMaestro » Articles
Viewing all articles
Browse latest Browse all 7

Asynchronous Message Handling in MFC

$
0
0

The issue I’m going to describe is sort of a solution to an inherited problem in the MFC programming environment. According to the MFC architecture, all messages are handled synchronously. Of course, this issue makes no difference in the case that for every single message you want to process, the processing will take you only a short time.

Lengthy processing (lets say, more than half a second) of one of your messages might result in a poor functioning program. For example, if after the user of your application presses an OK button, it will take you more than a moment to decide what to do next, and the user won’t even be able to move the application window. This is because when you process your message (OK key press), you block the processing of all other messages in your application!

This could be even more horrible if your program does some sort of computation or network management task that might take even longer to finish. Another example is showing some kind of animation on your application window.

One standard solution to this problem might be to use multi-threading. This is actually a solution many programmers employ. However, we all know the disadvantages of multi-threaded programming – Employing such an approach will make your code uglier, and in some cases, you might even run into bugs just because of the fact that you used multi-threading.

A more elegant solution for this problem is written on the following lines:

void AsynchronousMessageProcessing() {
	MSG msg;
	while (::PeekMessage(&msg, NULL, NULL, NULL, PM_NOREMOVE)) {
		AfxGetThread->PumpMessage();
	}
}

As you might have noticed, this code simply handles all messages waiting in the message queue. A simple call to AsynchronousMessageProcessing() once in a while, when you do your lengthy processing, will solve the problem easily.

I have this function in my “Tools” library and use it whenever I can.


Viewing all articles
Browse latest Browse all 7

Trending Articles