ManualResetEvent.Set() 什么时候可以返回 false?
根据 MSDN 文档,ManualResetEvent(或任何 EventWaitHandle)上的 Set() 和 Reset() 返回一个布尔指示符,无论操作是否成功。
在什么情况下这个调用会返回 false,如果返回 false,我该怎么办?
According the the MSDN documentation, Set() and Reset() on ManualResetEvent (or any EventWaitHandle) returns a boolean indicator whether or not the operation was successful.
Under which circumstances can this call return false, and what am I supposed to do if it does?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定如何回答这个问题,并且查看了很多 MSDN 示例,Set 返回值被忽略,因此它一定不重要或不太可能发生。
但这还不够好。我启动了虚拟机,然后打开 Reflector 来查看代码。 ManualResetEvent 没有 Set,但它继承自具有 Set 的 EventWaitHandle。代码如下:
SetEvent 是从 Kernel32 导入的:
WinIOError() 调用仅调用我们并不真正关心的 GetLastWin32Error 。基本上,这意味着对于返回 false 的调用,Win32 本机代码中必须发生一些非常错误的事情。
将此信息与官方 MSDN 文档中托管的代码忽略返回值的事实放在一起(为什么不呢?如果内核无论如何都失败了,你要做什么?),如果你想清理你的逻辑,你可以放心地自己忽略它如果你特别迂腐的话,咬一下或者得到它并记录下来。
I wasn't sure how to answer this and looking at a lot of MSDN examples the Set return value is ignored so it must not be important or likely to happen.
But that wasn't good enough. I fired up my VM and I opened up Reflector to take a look at the code. ManualResetEvent doesn't have Set but it inherits from EventWaitHandle which does. Here's the code:
Where SetEvent is imported from Kernel32:
The WinIOError() call just calls GetLastWin32Error which we don't really care about. Basically this means for the call to return false, something pretty wrong would have had to have occurred in the Win32 native code.
Putting this info together with the fact that code hosted in official MSDN documentation ignores the return value (why not? what are you going to do if the kernel fails anyway?) you can safely ignore it yourself if you want to clean your logic up a bit or get it and log it if you're especially pedantic.
我不确定仅记录错误并继续执行就足够了。 Set() 的错误结果可能会给等待处理程序管理的线程同步带来错误的行为。这就是多线程...我处理 false Set() 结果的愿景 - 抛出异常,在大多数情况下可能无法处理。
I am not sure that just log error and continue execution would be enought. False result from Set() can bring wrong behaviour in threads synchronozation managed by wait handlers. That is multithreading... My vision of handling false Set() result - throw exception, which probably in most cases can be unhandled.