.NET IDisposable接口

IDisposable界面是在C#.NET中释放Unmonaged资源。

IDisposable接口用于释放非托管资源。
此框架将在检测到对象不再需要的时候马上删除并自动释放内存。
当不再使用该对象时,垃圾收集器会自动释放分配给托管对象的内存,只有一个名为Dispose的单个成员。
当对象需要释放时调用此方法。

.NET IDisposable接口示例

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Drawing.Printing;
 
public class dispo
{
    public static void Main()
    {
        textfile1 textfile = new textfile1("c:\demo.txt");
        textfile.insertvalue("IDisposable示例");
 
        textfile.Dispose();
        textfile = null;
        Console.WriteLine("按回车回收垃圾");
        GC.Collect();
 
        Console.WriteLine("按回车退出");
        Console.ReadLine();
    }
}
 
public class textfile1 : IDisposable
{
    private FileStream str;
    private bool id;
    public textfile1(string filename)
    {
        str = new FileStream("test.txt", FileMode.OpenOrCreate);
        Console.WriteLine("Object " + GetHashCode() + " created.");
        Console.WriteLine("Using file: " + filename);
    }
 
    public void insertvalue(string buf)
    {
        if (id == true)
        {
            throw new ObjectDisposedException("已处理过");
        }
 
        StreamWriter wr = new StreamWriter(str);
        wr.WriteLine(System.DateTime.Now);
        wr.WriteLine(buf);
        wr.Close();
    }
 
    public void Dispose()
    {
        if (id == true)
            return;
 
        str.Close();
        str = null;
 
        id = true;
 
        GC.SuppressFinalize(this);
 
        Console.WriteLine("Object " + GetHashCode() + " disposed.");
    }
}
日期:2020-04-11 23:03:40 来源:oir作者:oir