Flickr Photos

Wordpress Stuff

Archive for September, 2007

Creating a background thread in MFC is pretty simple but there is a little trick. Don’t forget to create a InitInstance() virtual function as well as the Run() function. The MFC CWinThread initialization process calls InitInstance() when it first creates the thread and expects a TRUE return value. The default function returns FALSE so the thread will not start. Here is some simple code to start a background thread using MFC.

You can simply call the CreatThread() function on the object (inherited from CWinThread) but that starts the thread immediately and does not give you an opportunity to perform any initialization on the contents of the object and can sometime cause a race condition. A nice way to start the thread [I think] is to start it suspended, do some initialization and then resume it. I have set the m_bAutoDelete to false so that when the thread is finished I can still access the contents of the class to get the results, but that’s optional. Setting it to true (the default) means that when the thread terminates the object will automatically be deleted.