I have a thread running in my application. Inside the thread I am waiting on an auto reset event to exit. I want to make sure that i close the handle of the event after i use it. Ihave two options.
CloseHandle
of the event immediately after calling SetEvent
CloseHandle
after the line WaitForSingleObject
Please suggest me which one is the right approach.
Close the handle when all threads have finished using it. After the WaitForSingleObject sounds sensible to me (because if it succeeds, the SetEvent must have completed).
Alternatively - give each thread its own copy of the handle (eg via DuplicateHandle) and have each close their copy when they're finished. That's much harder to get wrong and requires less analysis of the code.
Calling CloseHandle
after SetEvent
doesn't make sense to me. You should (if required) call CloseHandle
after WaitForSingleObject
only.
Close event handle when you are sure that event has done its job and is not needed any more. In you case that is after you detect it has been set. So, close event handle after WaitForSingleObject
unblocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With