c# object.Dispose() 或 object = null

标签 c# .net dispose

您好,我有一个对象是一次性的,我想知道哪个更好:

this.object.Dispose();

this.object = null;

this.object.Dispose();
this.object = null;

最佳答案

Dispose 更好,更好的方法是使用 using 中的对象阻止并让框架处理它。

对于:this.object.Dispose();this.object = null;

将对象设置为 null 可能会导致遗漏未处理的非托管资源。 IDisposable 的全部目的是确保非托管资源在使用后被处置

参见:IDisposable - MSDN

The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

关于c# object.Dispose() 或 object = null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18317747/

相关文章:

c# - Entity Framework 代码首次迁移 : get sql scripts programmatically

c# - 是否应该对 Dispose 方法进行单元测试?

c# - WinForms 和处理自定义控件

c# - 如何获取DeleteUrlCacheEntry()错误代码? (或者有关为什么特定删除不起作用的其他信息)?

c# - .NET MAUI Android 中的通知图标

C# SqlCommand Connection.Open() 问题

c# - unicode 字符代码的 uint 和 char 转换

c# - Data Context 的 SubmitChanges 方法导致实体引用设置为 null

c# - 在公开 Begin/End 方法的类中实现 IDisposable

c# - 从 Amazon AWS S3 下载对象时流仅部分读取