Quote Originally Posted by Igor Vartanov View Post
And yes, the answer to your question is: you need to send LVM_INSERTITEM message from your worker thread to the list view control to add an item. Windows API is thread safe. MFC is not.
I would tend to disagree with this recommendation, and instead I would prefer Arjay's suggestion:
Quote Originally Posted by Arjay
Use notification messages to communicate between the worker threads and main thread.
The problem with sending (SendMessage) an LVM_INSERTITEM from the worker thread to the UI thread is that the sending of the message will halt the worker thread until the UI thread returns a result. This has the big potential for thread lock if, for example, the UI thread is waiting on something else and is never able to send a response.

In other words, when using SendMessage, since the worker thread must wait for a response from the UI thread, there is far too much interaction between the worker thread and the UI thread.

Arjay's suggestion, on the other hand, is a clean break between the worker and UI threads. Use notification messages that you design for yourself.

One way to implement Arjay's suggestion is for the worker to allocate some memory on the heap (using "new", for example), and to store information in it that the worker wants the UI to have access to. The worker then posts (post using PostMessage, don't send using SendMessage) a custom notification message to the UI thread, using the LPARAM or WPARAM to store the address of the memory. The UI responds to the custom message by retrieving the memory, using it in some way (such as by inserting the answer x=1 into a list view, where the value of "1" was stored in the memory allocated by the worker), and then finally by free'ing the allocated memory (using "delete", for example).

The advantages to this framework include a very clean break between the UI and the worker. For example, since the worker is using PostMessage, it does not wait for the UI before proceeding with the next line of code. As a consequence, the worker will never freeze, even if the UI has become frozen (or indeed, even if the UI thread does not even exist). Likewise, the UI thread expects nothing from the worker, but if indeed it receives the custom notification message, it knows exactly how to respond.

Mike

PS: Note that you cannot PostMessage an LVM_INSERTITME from the worker to the UI, since the information contained in the LVM_INSERTITEM message will probably be out of scope by the time that the UI acts on the message.