Using User-Interface Threads

Terminating the loop & hazards

Terminating the loop

So we know how to start the thread, and initialize the thread, but how do we stop the thread? Just like any other message pump, as it turns out. Just post a WM_QUIT message. It is unfortunate that Microsoft has not chosen to be consistent, but they actually require in the PostThreadMessage that you explicitly provide the WPARAM and LPARAM values, which are, in this case, 0. So when you get to the point where you are read to shut down the thread, just do

    thread->PostThreadMessage(WM_QUIT, 0, 0);

and the thread shuts down.

Hazards

It is a bad idea to mix thread control using PostThreadMessage and UI objects such as message boxes and dialog boxes. When a thread message is received by GetMessage, it has a NULL window handle. This means that it cannot be dispatched via DispatchMessage. Special handling is required for thread messages, which is built into the message pump of CWinThread::Run. What this means is that if you call DoModal or AfxMessageBox, MessageBox, or any similar function that spawns a new message loop any posted thread messages will be lost. Microsoft suggests using a message hook function to intercept messages under these conditions. Consequently, if you are going to use PostThreadMessage to a UI thread, you should follow the advice given in my essay about worker threads and treat the UI thread as if it were a worker thread insofar as spawning child dialogs.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” - Rich Cook