idisposable.dispose()是自动调用的吗?
可能的重复:
垃圾收集器会呼叫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
为您的类用户提供了一种方法,可以尽早发布资源,而不是等待垃圾收集器。客户端的最佳方法是使用
使用
语句使用语句,该语句即使有例外,也可以处理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.如果您在语句中在
中实例化对象,则当代码退出
使用 block时,请拨打(),如果您不使用
使用
使用,然后取决于您(调用代码)通过明确调用dispose()来处理对象。另外,如果您的呼叫者不调用Dispose(),则您(MyObject的实现者)可以添加对最终化器的支持。更多信息在这里。
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”将在范围末尾自动处置。
使用
语句的优点(与调用Dispose()显式相比)是dispose()
无论您如何退出此块:通过经过末端,遇到返回
语句或抛出异常。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
和调用在Destructor(finalizer)中处置
。To make sure the resources are correctly disposed, you need to both implement
IDisposable
and callDispose
in the destructor(finalizer).