开发者

terminating thread gracefully on main app termination

开发者 https://www.devze.com 2022-12-30 03:27 出处:网络
I have a modelless dialog that creates开发者_如何学JAVA a thread, and if the cancel button in the dialog is hit,a variable bCancel is set which the thread in question periodically checks, and then imm

I have a modelless dialog that creates开发者_如何学JAVA a thread, and if the cancel button in the dialog is hit, a variable bCancel is set which the thread in question periodically checks, and then immediately jumps to its clean up code. It works fine. I can even send a WM_COMMAND...ID_CANCEL to the dialog from other places and it works the same. But its not working when I try to send ID_CANCEL to the dialog from the main application window's WM_CLOSE handler (i.e. the user is trying to shut the entire application down while this thread is running.) As best I can tell something is just terminating the thread from outside before it can execute its cleanup code. Does this sound right. What can I do.

(There's a critical section in the dialog's ID_CANCEL handler I didn't mention - not sure how relevant it is. (bCancel is set within this critical section and the thread executes its clean up code within the same critical section.)


Not that anyone's still interested, but in the main app WM_CLOSE handler I set bCloseApp=TRUE, then send ID_CANCEL to the dialog and then check if the thread is active. If it is I return 0 (thus bypassing the default DestroyWindow of WM_CLOSE.) Then in the thread exit code I PostMessage(...WM_CLOSE...) to the main app window if bCloseApp==TRUE.

Before implementing the above I found that while in the main app's WM_CLOSE handler, the thread in question is automatically suspended for some reason (which surprised me) and that was a complicating factor as I couldn't wait for the thread to terminate while in the WM_CLOSE handler.


After setting the thread's bCancel, your dialog code should wait for the thread handle to get signaled (thus destroyed), so you can use one of the wait### functions on the thread handle (with a sane timeout value of course), thus the app will wait a tiny bit for your thread cleanup to get called.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号