我需要调用Close()在ManualResetEvent的? [英] Do I need to call Close() on a ManualResetEvent?

查看:254
本文介绍了我需要调用Close()在ManualResetEvent的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直对.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的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆