关键词搜索

源码搜索 ×
×

C# 正确实现 IDisposable实现资源释放

发布2018-06-04浏览6102次

详情内容

文章来自:https://msdn.microsoft.com/zh-cn/library/ms244737(v=vs.80).aspx

正确实现IDisposable原因

未正确实现 IDisposable。下面列出了产生此问题的一些原因:

  • IDisposable 在类中重新实现。

  • Finalize 被再次重写

  • Dispose 被重写。

  • Dispose() 不是公共、密封或命名的 Dispose。

  • Dispose(bool) 不是受保护的、虚拟的或未密封的方法。

  • 在未密封类型中,Dispose() 必须调用 Dispose(true)。

  • 对于未密封类型,Finalize 实现不调用 Dispose(bool) 和事例类终结器中的一个或两个。

  1. 与上述任何模式冲突都将触发此警告。

  2. 每个未密封的根 IDisposable 类型都必须提供其各自的受保护虚拟 void Dispose(bool) 方法。Dispose() 应当调用 Dipose(true),Finalize 应当调用 Dispose(false)。如果创建未密封的根 IDisposable 类型,必须定义 Dispose(bool) 并调用它。

  3. 下面的伪代码提供一个说明如何在使用托管和本机资源的类中实现 Dispose(bool) 的常规示例。

  1. public class Resource : IDisposable
  2. {
  3. private IntPtr nativeResource = Marhsal.AllocHGlobal(100);
  4. private AnotherResource managedResource = new AnotherResource();
  5. // Dispose() calls Dispose(true)
  6. public void Dispose()
  7. {
  8. Dispose(true);
  9. GC.SuppressFinalize(this);
  10. }
  11. // NOTE: Leave out the finalizer altogether if this class doesn't
  12. // own unmanaged resources itself, but leave the other methods
  13. // exactly as they are.
  14. ~Resource()
  15. {
  16. // Finalizer calls Dispose(false)
  17. Dispose(false);
  18. }
  19. // The bulk of the clean-up code is implemented in Dispose(bool)
  20. protected virtual void Dispose(bool disposing)
  21. {
  22. if (disposing)
  23. {
  24. // free managed resources
  25. if (managedResource != null)
  26. {
  27. managedResource.Dispose();
  28. managedResource = null;
  29. }
  30. }
  31. // free native resources if there are any.
  32. if (nativeResource != IntPtr.Zero)
  33. {
  34. Marshal.FreeHGlobal(nativeResource);
  35. nativeResource = IntPtr.Zero;
  36. }
  37. }
  38. }

规则说明

所有的 IDisposable 类型都应当正确实现 Dispose 模式。

检查代码并确定下面的哪些解决方案能够修复此冲突。

  • 从 {0} 实现的接口列表中移除 IDisposable,而改为重写基类 Dispose 实现。

  • 从类型 {0} 中移除终结器,重写 Dispose(bool disposing),并在“disposing”为 false 的代码路径中放入终结逻辑。

  • 移除 {0},重写 Dispose(bool disposing),并在“disposing”为 true 的代码路径中放入释放逻辑。

  • 确保将 {0} 声明为 public 和 sealed。

  • 将 {0} 重命名为“Dispose”,并确保将它声明为 public 和 sealed。

  • 确保将 {0} 声明为 protected、virtual 和 unsealed。

  • 修改 {0} 以便它调用 Dispose(true),然后对当前对象实例(在 Visual Basic 中为“this”或“Me”)调用 GC.SuppressFinalize,然后返回。

  • 修改 {0} 以便它调用 Dispose(false),然后返回。

  • 如果编写未密封的根 IDisposable 类,请确保 IDisposable 的实现遵循上面描述的模式。

不要排除与该规则有关的警告。



相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载