开发者

Is it safe to Dispose() an EventWaitHandle after it has been signalled?

开发者 https://www.devze.com 2023-02-16 18:19 出处:网络
I have a situation where I\'m creating a number of IDisposable objects that encapsulate an EventWaitHandle instance each, so that various interested parts of my app can wait on them. This instance is

I have a situation where I'm creating a number of IDisposable objects that encapsulate an EventWaitHandle instance each, so that various interested parts of my app can wait on them. This instance is not directly accessible to any code outside of its owner object. It can only be accessed indirectly through wrapper calls.

Once an object signals it's done, it is no longer useful, so it is disposed by a central manager object and tossed from its list of references.

The question now is, what to do with the encapsulated EventWaitHandle? Naturally, it should be disposed as well, and sooner rather than later, to prevent my app from leaking开发者_运维知识库 OS handles.

But is it safe to do that synchronously, immediately after the event is signaled by its owner object? What can happen if there are threads still waiting to be released (i.e. blocking inside a call to WaitOne())?

What is the recommended approach here?


I guess it's time to close this one with my own findings.

I couldn't find any direct guidelines in the docs, but decided to follow the information I extracted from Raymond Chen's blog. In his posts (I forget the exact links) he mentions Win32 API rules dictate that event's handle must remain valid for the duration of waiting. In unmanaged world this means at least one handle to the event must remain open.

AFAIU, .NET's implementation uses Win32 API under the hood, with each EventWaitHandle instance corresponding to a separate unmanaged event. When EventWaitHandle.Dispose() closes the only handle to the underlying unmanaged event, this effectively renders the event instance invalid.

In short, the right approach seems to be to build a parallel infrastructure through which event publisher can notify potential listeners that event will be going away soon. The publisher must then wait until all the listeners have "unsubscribed" (i.e. stopped waiting) before proceeding to Dispose() the event instance.

It's a lot of book-keeping, but ultimately, it only seems right. Hope this helps clear things for others, too.

0

精彩评论

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

关注公众号