How to let a user cancel a thread at any time.

Here's a problem I encounter very often in GUI programming and I'm not even sure how to google it.

A task is executing. While it does so I display a dialog that tells the user what is going on. The dialog has a cancel button. Since I can't be in the message loop while executing the given task, the dialog executes in its own thread.

The problem is, how does the task know when the user has hit the cancel button. I don't want to have keep polling an event. What's more, sometimes there is a separate error handling function (when the main function is retrying the task several times) which the function executing the task shouldn't know about.

I'm sure there must be a simple elegant solution to such situations. If anyone can help I'd be grateful.

Thanks for your reply. I didn't know about the MsgWaitForMultipleObjects API. What I've done is create a thread in the error handler, pass it an event, have the thread create a dialog and, in the main thread, poll the event regularly. In the dialog thread the thread uses MsgWaitForMUltipleObjects to process messages while polling the event. If the user cancels the dialog thread sets the event. If the operation succeeds the main thread sets the event which the dialog thread then ends the dialog and thread.