IDisposable.Dispose() 会自动调用吗?
我有一个类,其中有一些非托管资源。我的类实现了 IDisposable 接口并在 Dispose() 方法中释放非托管资源。我是否必须调用 Dispose()
方法还是会以某种方式自动调用它?垃圾收集器会调用它吗?
Possible Duplicate:
Will the Garbage Collector call IDisposable.Dispose for me?
I have a Class which has some unmanaged resources. My class implements the IDisposable
interface and releases the unmanaged resources in the Dispose()
method. Do I have to call the Dispose()
method or will it be automatically called somehow? Will the Garbage Collector call it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Dispose()
不会自动调用。如果有终结器,它将被自动调用。实现IDisposable
为类的用户提供了一种提前释放资源的方法,而不是等待垃圾收集器。对于客户端来说,更好的方法是使用
using
语句来处理Dispose()
的自动调用,即使存在异常也是如此。IDisposable
的正确实现是:如果类的用户调用
Dispose()
,则直接进行清理。如果对象被垃圾收集器捕获,它会调用Dispose(false)
进行清理。请注意,当从终结器(~MyClass
方法)调用时,托管引用可能无效,因此只能释放非托管资源。Dispose()
will not be called automatically. If there is a finalizer it will be called automatically. ImplementingIDisposable
provides a way for users of your class to release resources early, instead of waiting for the garbage collector.The preferable way for a client is to use the
using
statement which handles automatic calling ofDispose()
even if there are exceptions.A proper implementation of
IDisposable
is:If the user of the class calls
Dispose()
the cleanup takes place directly. If the object is catched by the garbage collector, it callsDispose(false)
to do the cleanup. Please note that when called from the finalizer (the~MyClass
method) managed references may be invalid, so only unmanaged resources can be released.如果您在
using
语句中实例化对象,则当代码退出using
块时,系统会为您调用 Dispose()如果您不使用
using
>,然后由您(调用代码)通过显式调用 Dispose() 来处置您的对象。另外,您(MyObject 的实现者)可以添加对终结器的支持,以防您的调用者不调用 Dispose()。更多信息请参见此处。
If you instantiate your object in a
using
statement, Dispose() is called for you when code exits theusing
blockIf you don't use
using
, then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().Also, you (the implementor of MyObject) can add support for a finalizer in case your caller doesn't call Dispose(). More info here.
您将必须手动调用此方法,也许(假设“MyClass”实现“IDisposable”)在像
C# 8.0这样的构造中,您可以编写如下语句:
并且“myclass”将在范围末尾自动处理。
using
语句的优点(与显式调用 Dispose() 相比)是,无论您如何退出此块,都会调用Dispose()
:通过运行到末尾,遇到return
语句或抛出异常。You will have to call this method manually, maybe (assuming that "MyClass" implements "IDisposable") in a construct like
In C# 8.0, you can write as below statement:
and the "myclass" will be disposed automatically at the end of the scope.
The advantage of the
using
statement (compared to calling Dispose() explicitly) is thatDispose()
is called no matter how you exit this block: by running past the end, encountering areturn
statement or having an exception thrown.为了确保资源被正确处置,您需要实现
IDisposable
并在析构函数(终结器)中调用Dispose
。To make sure the resources are correctly disposed, you need to both implement
IDisposable
and callDispose
in the destructor(finalizer).