WaitForSingleObject() may be a quick fix but any program and future projects that uses such processing will always benefit from using multiple threads. It really doesn't take that much to implement a separate thread and, once done, the results are well worth the effort.
[tt]
// First, create some kind of structure to control
// and prime your thread. As a simple example, this
// will be some kind of progress bar which increments
// the bar by 5% every half second
struct MyThreadStruct
{
unsigned progAmt;
bool abort;
};
// To create a thread using MFC (which I'm assuming
// you are) you need to have a CWinThread* member in
// your class that you'll be spawning the thread from.
// For example, suppose you'll be wanting to spawn
// your thread from a dialog box, you will probably
// have your dialog's class with the CWinThread* member
// and controlling structure in it like so:
class MyDialogClass : public CDialog
{
......
// <- usual stuff here
public:
static UINT MyThreadFunction(LPVOID);
CWinThread* mThread;
MyThreadStruct mControl;
};
// This function is the one that the thread runs in
// it takes an LPVOID parameter so you can more or
// less pass anything in - this is usually some kind
// of structure which will contain all the details
// that the tread needs to run
// This function can either be global or a static
// member function of a class
UINT MyDialogClass::MyThreadFunction(LPVOID param)
{
MyThreadStruct* info = (MyThreadStruct*)param;
while (!info->abort && progAmt<100)
{
// paint the progress bar using
// info->progAmt as the amount
info->progAmt += 5;
// increment by 5%
::Sleep(500)
// sleep for half second
}
return (0);
}
// Now when it comes to spawning your thread, you'll
// use the ::AfxBeginThread() function and pass in the
// name of your thread processing function and the
// address of whatever structure you created to prime
// and control the thread.
// So, somewhere in your dialog's class code you need
// to spawn the thread and kick it off running.
// Perhaps this can be done when the user clicks a
// button or something!
void MyDialogClass::OnClickStartButton()
{
// first prime the controlling structure
mControl.abort = false;
mControl.progAmt = 0;
// spawn the thread and begin running it
mThread = ::AfxBeginThread(
MyDialogClass::MyThreadFunction,
(LPVOID)&mControl);
}
// Now suppose you dialog has a button for suspending
// and resuming the thread. You can use the functions
// SuspendThread() and ResumeThread() to pause and
// resume it.
void MyDialogClass::OnClickPauseButton()
{
// pause the thread but do not kill it
mThread->SuspendThread();
}
// If you want to stop the thread altogether...
void MyDialogClass::OnClickStopButton()
{
mControl->abort = true;
}[/tt]
programmer (prog'ram'er), n A hot-headed, anorak wearing, pimple-faced computer geek.