来自MSDN官方文档:http://msdn.microsoft.com/en-us/library/system.configuration.provider.providercollection.aspx

 using System;
using System.ComponentModel; // The following example demonstrates how to create
// a resource class that implements the IDisposable interface
// and the IDisposable.Dispose method. public class DisposeExample
{
// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public class MyResource: IDisposable
{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component component = new Component();
// Track whether Dispose has been called.
private bool disposed = false; // The class constructor.
public MyResource(IntPtr handle)
{
this.handle = handle;
} // Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
} // Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
} // Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero; // Note disposing has been done.
disposed = true; }
} // Use interop to call the method necessary
// to clean up the unmanaged resource.
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle); // Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
}
public static void Main()
{
// Insert code here to create
// and use the MyResource object.
}
}

一种处理非托管资源的经典模式:

当手动调用Dispose时,要释放该对象的托管和非托管的资源;

当CG调用Dispose时,要释放该对象的非托管资源,以防遗漏

C# 实现IDisposable的模式的更多相关文章

  1. .net中的线程同步基础(搬运自CLR via C#)

    线程安全 此类型的所有公共静态(Visual Basic 中为 Shared)成员对多线程操作而言都是安全的.但不保证任何实例成员是线程安全的. 在MSDN上经常会看到这样一句话.表示如果程序中有n个 ...

  2. 实现IDisposable接口的模式

    代码: public class Class2 : IDisposable { ~Class2() { Dispose(false); } public void Dispose() { Dispos ...

  3. C#中的IDisposable模式

    当谈到垃圾回收,在C#中,托管资源的垃圾回收是通过CLR的Garbage Collection来实现的,Garbage Collection会调用堆栈上对象的析构函数完成对象的释放工作:而对于一些非托 ...

  4. MVC视图展现模式之移动布局解析-续集

    网站就必须用响应式布局吗?MVC视图展现模式之移动布局:http://www.cnblogs.com/dunitian/p/5213787.html demo:http://pan.baidu.com ...

  5. 通过IEnumerable和IDisposable实现可暂停和取消的任务队列

    一般来说,软件中总会有一些长时间的操作,这类操作包括下载文件,转储数据库,或者处理复杂的运算. 一种处理做法是,在主界面上提示正在操作中,有进度条,其他部分不可用.这里带来很大的问题, 使用者不知道到 ...

  6. External Configuration Store Pattern 外部配置存储模式

    Move configuration information out of the application deployment package to a centralized location. ...

  7. 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  8. IDisposable的另类用法

    IDisposable是.Net中一个很重要的接口,一般用来释放非托管资源,我们知道在使用了IDisposable的对象之后一定要调用IDisposable.Dispose()方法,或者使用.Net提 ...

  9. 分享基于Entity Framework的Repository模式设计(附源码)

    关于Repository模式,在这篇文章中有介绍,Entity Framework返回IEnumerable还是IQueryable? 这篇文章介绍的是使用Entity Framework实现的Rep ...

随机推荐

  1. postman断言的几种方式(二)

    1.检查响应体是否包含字符串 pm.test("Body matches string", function () { pm.expect(pm.response.text()). ...

  2. html5 canvas loading(这可怕的编辑器,自动把我的canvas转义了)---以前收藏的整理了一下

    /* super inefficient right now, could be improved */ var c = document.getElementById('canvasload'), ...

  3. 将网页设置为允许 XMLHttpRequest 跨域访问

    在非IE下,使用XMLHttpRequest 不能跨域访问, 除非要访问的网页设置为允许跨域访问. 将网页设置为允许跨域访问的方法如下: Java Response.AddHeader("A ...

  4. iOS常用小功能

    CHENYILONG Blog 常用小功能 技术博客http://www.cnblogs.com/ChenYilong/ 新浪微博http://weibo.com/luohanchenyilong  ...

  5. JavaScript 中创建三种消息框:警告框、确认框、提示框。

    网址:http://www.w3school.com.cn/js/js_popup.asp 警告框 警告框经常用于确保用户可以得到某些信息. 当警告框出现后,用户需要点击确定按钮才能继续进行操作. 语 ...

  6. django错误笔记——1242 Subquery returns more than 1 row

    在数据库查询操作过程中,子查询结果不唯一,导致外面的查询无法进行. 我的错误语句: rid = models.User.objects.filter(username=username).values ...

  7. requests(三):json请求中中文乱码处理

    最近收到一个问题:json格式请求数据中有中文,导致服务端签名失败. 问题详情: 一位同学在发送json格式的post请求时,请求数据中有中文内容: {"inputCodes":[ ...

  8. 奈奎斯特定理 and 香农定理

    -----------------------整理自<21ic电子网> 奈奎斯特定理(Nyquist's Theorem)和香农定理(Shannon's Theorem)是网络传输中的两个 ...

  9. H5开发APP考题和答案

    { "last_updated": { "$date": 1544276670569 }, "page_count": 1, "a ...

  10. 关于NotificationListenerService监听时有失败的处理

    关于NotificationListenerService监听时有失败的处理 问题由来 去年进入一家专业做智能穿戴设备的公司,在项目中需要监听系统通知栏变化(主要是IM类app的信息获取到后推送到用户 ...