我一直对.NET线程读取并正在制定一个使用的 ManualResetEvent的。我发现很多在互联网上的代码示例。然而,阅读的WaitHandle 的文档时,我看到了以下内容:
I've been reading up on .NET Threading and was working on some code that uses a ManualResetEvent. I have found lots of code samples on the internet. However, when reading the documentation for WaitHandle, I saw the following:
的WaitHandle实现的Dispose 模式。见实施完成并处置以清理非托管资源。
WaitHandle implements the Dispose pattern. See Implementing Finalize and Dispose to Clean Up Unmanaged Resources.
似乎都不来电。关闭()对他们创造的ManualResetEvent的对象的即使是好的递归和并发从pfxteam博客文章的(的修改 - 这已经using块我已经错过的)。这只是例子疏忽,还是不需要?我很好奇,因为一个WaitHandle的封装操作系统特定的对象,所以很容易被一个资源泄漏。
None of the samples seem to call .Close() on the ManualResetEvent objects they create, even the nice Recursion and Concurrency article from the pfxteam blog (Edit - this has a using block I has missed). Is this just example oversight, or not needed? I am curious because a WaitHandle "encapsulates operating system–specific objects," so there could easily be a resource leak.
推荐答案在一般来说,如果一个对象实现的IDisposable 它这样做是有原因的,你应该叫的Dispose (或关闭,视情况而定)。在这个例子中,你的网站,ManualResetEvent的被包裹在使用语句,这将自动句柄上调用的Dispose 里面。在这种情况下,关闭与的Dispose (这是大多数的IDisposable ,提供了一个关闭方法实现)
In general, if an object implements IDisposable it is doing so for a reason and you should call Dispose (or Close, as the case may be). In the example you site, the ManualResetEvent is wrapped inside a using statement, which will "automatically" handle calling Dispose. In this case, Close is synonymous with Dispose (which is true in most IDisposable implementations that provide a Close method).
从示例代码:
using (var mre = new ManualResetEvent(false)) { ... }扩展到
var mre = new ManualResetEvent(false); try { ... } finally { ((IDispoable)mre).Dispose(); }更多推荐
我需要调用Close()在ManualResetEvent的?
发布评论