将 AutoResetEvent 对象包装在受限的 WaitHandle 中?
我构建了一个库,它启动一个线程来完成它的事情并向调用者返回一个 WaitHandle。
查看错误报告,我怀疑调用我的库的代码正在获取返回的对象并将其转换为 AutoResetEvent (它就是)并引发标志本身。它不是故意这样做的。
有没有一种方法可以将 AutoResetEvent 对象包装为仍然可以 WaitOne'd 和 WaitAny'd 的对象,但只能由我的代码引发?
谢谢。
I've built a library that launches a thread to do it's thing and returns a WaitHandle to the caller.
Looking at a bug report, I suspect the code that's calling my library is taking the returned object and casting it to an AutoResetEvent (which it is) and raising the flag itself. It's not meant to do that.
Is there a way I can wrap the AutoResetEvent object with one that can still be WaitOne'd and WaitAny'd, but can only be raised by my code?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个从
EventWaitHandle
派生的新类,并重写Set
和Reset
,以便它们不执行任何操作或引发异常。实际上,您必须创建新的实现,因为 Set 和 Reset 不是虚拟的。当然,您必须创建自己的其他名称的方法。就像MyInternalSet
和MyInternalReset
一样。可能,但我不建议这样做。相反,我会记录客户端不应设置或重置事件,因为这样做会导致不可预测的行为。
您可以创建一个
WaitHandle
派生类,将AutoResetEvent
作为内部
属性保存。客户端代码将无法访问它。类似于:您必须重写受保护的
Dispose(Boolean)
方法,以便它将处理内部句柄,并且您需要其他WaitOne
重载,以及。然后,您可以创建Set
和Reset
的内部
实现,或者只是让您的代码调用InternalHandle.Set
。我仍然认为最好的做法是告诉客户不要这样做。但如果你必须阻止它,上面的方法应该有效。
You can create a new class derived from
EventWaitHandle
and overrideSet
andReset
so they do nothing, or throw an exception. Actually, you would have to createnew
implementations, sinceSet
andReset
aren't virtual. Of course, you'd have to create your own, other-named methods. LikeMyInternalSet
andMyInternalReset
. Possible, but I wouldn't recommend doing it.Instead I would document that the client should not set or reset the event, because doing so will cause unpredictable behavior.
You could create a
WaitHandle
-derived class that holds yourAutoResetEvent
as aninternal
property. Client code then wouldn't be able to access it. Something like:You'll have to override the protected
Dispose(Boolean)
method, so that it will dispose the internal handle, and you'll want the otherWaitOne
overloads, as well. You can then createinternal
implementations ofSet
andReset
, or just have your code callInternalHandle.Set
.I still think the best course of action is to tell the client not to do that. But if you must prevent it, the above should work.