简体   繁体   English

调用SetEvent后调用CloseHandle

[英]Calling CloseHandle after calling SetEvent

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. 我有两个选择。

  1. Calling CloseHandle of the event immediately after calling SetEvent 在调用SetEvent后立即调用事件的CloseHandle
  2. Calling CloseHandle after the line WaitForSingleObject WaitForSingleObject行之后调用CloseHandle

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). WaitForSingleObject对我来说听起来很合理(因为如果成功,SetEvent必须已经完成)。

Alternatively - give each thread its own copy of the handle (eg via DuplicateHandle) and have each close their copy when they're finished. 或者 - 为每个线程提供自己的句柄副本(例如,通过DuplicateHandle),并在完成后分别关闭它们的副本。 That's much harder to get wrong and requires less analysis of the code. 这更容易出错并需要更少的代码分析。

Calling CloseHandle after SetEvent doesn't make sense to me. SetEvent之后调用CloseHandle对我来说没有意义。 You should (if required) call CloseHandle after WaitForSingleObject only. 您应该(如果需要)仅在WaitForSingleObject之后调用CloseHandle

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. 因此,在WaitForSingleObject解除阻塞之后关闭事件句柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM