Using User-Interface Threads

Creating a UI thread

First, there is the question about how to create the thread. What you first need is a CWinThread-derived class, which is then necessarily a CCmdTarget-derived object. Use the ClassWizard to create it, and you will get all the correct declarations. For purposes of this essay, it will be called CMyThread.

Now, you would expect to use AfxBeginThread, in the approved fashion, doing

CMyThread * thread = AfxBeginThread(RUNTIME_CLASS(CMyThread));

Well, it isn't quite that easy. It should be, but it isn't. What's missing here is a way to pass initial parameters in to the thread! 

Consider a couple cases: you don't have a CMyThread object until the AfxBeginThread completes. But by the time you get control, the thread may already be running, and therefore it may be too late to set any values.

There are a couple solutions to this. One is to create the thread suspended, by providing the CREATE_SUSPENDED flag. Note that because this does not default we have to provide the intermediate parameters, the thread priority and the call stack size, so provide the values which are the defaults:

CMyThread * thread = AfxBeginThread(RUNTIME_CLASS(CMyThread),
                                    THREAD_PRIORITY_NORMAL,
                                    0, // stack size
                                    CREATE_SUSPENDED);

And upon completion, you can then set any member variables in the class, and explicitly resume the thread:

thread->m_Whatever = ...;
thread->m_OtherThing = ...;
thread->ResumeThread();

I chose to do the two-step method suggested in the AfxBeginThread documentation:

CMyThread * thread = new CMyThread();
thread->m_Whatever = ...;
thread->m_OtherThing = ...;
thread->CreateThread();

I did this just because I did not like to explicitly specify the defaults. 

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.

“Never trust a programmer in a suit.” - Anonymous