Implementing Finalize and Dispose to Clean Up Unmanaged Resources

本文介绍了如何在C#中使用Dispose模式来管理资源。通过基类和派生类的示例展示了如何正确释放托管和非托管资源,并遵循最佳实践避免内存泄漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 // Design pattern for a base class.
2 public class Base: IDisposable
3 {
4 private bool disposed = false;
5
6 //Implement IDisposable.
7 public void Dispose()
8 {
9 Dispose(true);
10 GC.SuppressFinalize(this);
11 }
12
13 protected virtual void Dispose(bool disposing)
14 {
15 if (!disposed)
16 {
17 if (disposing)
18 {
19 // Free other state (managed objects).
20 }
21 // Free your own state (unmanaged objects).
22 // Set large fields to null.
23 disposed = true;
24 }
25 }
26
27 // Use C# destructor syntax for finalization code.
28 ~Base()
29 {
30 // Simply call Dispose(false).
31 Dispose (false);
32 }
33 }
34
35 // Design pattern for a derived class.
36 public class Derived: Base
37 {
38 private bool disposed = false;
39
40 protected override void Dispose(bool disposing)
41 {
42 if (!disposed)
43 {
44 if (disposing)
45 {
46 // Release managed resources.
47 }
48 // Release unmanaged resources.
49 // Set large fields to null.
50 // Call Dispose on your base class.
51 disposed = true;
52 }
53 base.Dispose(disposing);
54 }
55 // The derived class does not have a Finalize method
56 // or a Dispose method without parameters because it inherits
57 // them from the base class.
58 }

转载于:https://www.cnblogs.com/hongyu/archive/2011/04/28/2031938.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值