|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
Introduction
Using the codeTo use the code you should derive your class from class CMyThread : public CThread { void Run(void* param); } It's OK if you want to derive from several classes, which is common if you want to run the thread in a dialog class: class CMyThread : public CDialog, CThread { void Run(void* param); } Starting the threadStarting the thread is very simple, just call You could send an optional parameter to the thread with a pointer. If you do this, make sure that the pointer is valid. The following example will not work: {
int parameter = 10;
Start(¶mater);
}
When you call {
int* parameter = new int(10);
Start(¶mater);
}
Don't forget to delete the object in Stopping the threadTo stop the thread, call Running the threadWhat the thread has to do is up to you. The thread will start its execution in void CMyThread::Run(void* param) { //Run the thread until someone has called Stop() while( ShouldRun() ) { ... } } Sending messages from a threadVery often you want to update the GUI from the thread. For example, you want to update a progress bar. The obvious solution is to update the progress bar directly from the thread. Example: void CMyThreadInDialog::Run(void* param) { ... m_progressbar.SetPos(10) ... } But this will not work. A golden rule in Windows is that only one thread should work with the GUI. Instead of this you should use messages. From the thread that is executing in So your code should look something like this: void CMyThreadInDialog::Run(void* param) { ... ::PostMessage(UPDATE_PROGRESSBAR, m_hWnd, 10, 0); ... } See the example for more details. Points of interestBefore I wrote this class, I looked for something similar in CodeProject. To my surprise, I didn't find any article on this topic. But I wasn't looking hard enough... There are at last two articles that provide a similar solution:
Even if I am not the first one to write an article on this topic, I hope someone finds this class useful :-). History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||