Questions on Dialog and threads.

I have a dialog box that is non-interactive, it just displays some information while it is doing a job. In the OnInitDialog() function I start a thread that will do all the work.

When the thread is finished, the dialog needs to exit with a return code. I know you can do a EndDialog(), but I heard that you should not do that from another thread, it should only be from the main thread.

Assuming this is the case, how can my thread cause an event to let my dialog know it is done? Should I just use a custom windows message, use an existing message, or some other mechanism?
[597 byte] By [DeepT] at [2007-11-20 11:36:55]
# 1 Re: Questions on Dialog and threads.
Use a custom window message that you post to your dialog just before your thread is finishing. When you receive this message in your dialog you will use ::WaitForSingleObject to wait till the thread is finished, when it is you can call EndDialog.

Also, check out this FAQ: Threads: How to end a thread? (http://www.dev-archive.com/forum/showthread.php?t=305166)

Laitinen
laitinen at 2007-11-10 22:25:00 >
# 2 Re: Questions on Dialog and threads.
If you have a dialog that starts and ends at the same time as the thread, why can't you use the dialog main thread ?
Skizmo at 2007-11-10 22:25:54 >
# 3 Re: Questions on Dialog and threads.
No... I failed to make myself clear.

I have a dialog box that is a status window.

I have 'work' which will take a while, maybe 30 seconds.

The 'work' will update the status via the dialog.

When the 'work' is done, I need the dialog associated with it to close.

Why not do it in the main thread? It will lock up the dialog box, and it will not get any WM_PAINT calls. Hence if update the status, no one will see it.

Ending the thread: I do not need help with this. Ending the thread is not the problem.

WaitForSingleObject will not work because it will bind the main thread, hence defeat the entire purpose of multi-threading here. If the main thread is bound up, then the message pump stops.

The problem is having my dialog react to the 'end' thread event by closing and returning a result from it's "doModal()" call. Since ending a thread doesn't cause an event, I am kind of stuck.

I suppose I could just 'hack' another unrelated event, such as the WM_PAINT to look for the thread status change and then issue the EndDialog() command. Not graceful, but it is all I can think of right now.
DeepT at 2007-11-10 22:27:03 >
# 4 Re: Questions on Dialog and threads.
Dear DeepT!
Haven't you read the laitinen's post?
Your worker thread should PostMessage a user defined message (or, as you wrote "a custom windows message") to the main dialog just before it (the thread) returns.
Then in the message handler of this message (in the dialog class) you should just call the EndDialog with any parameter you want.
VictorN at 2007-11-10 22:28:03 >