C#的垃圾回收

对于文件,数据库,网络等非.NET资源,要显式地释放资源,MSDN有个例子

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.
    }
}

可以用GC.Collect()用作回收,MSDN是这样说

If your managed objects reference unmanaged objects by using their native file handles, you have to explicitly free the managed objects, because the garbage collector tracks memory only on the managed heap.

Users of your managed object may not dispose the native resources used by the object.To perform the cleanup, you can make your managed object finalizable.Finalization consists of cleanup actions that you execute when the object is no longer in use.When your managed object dies, it performs cleanup actions that are specified in its finalizer method.

When a finalizable object is discovered to be dead, its finalizer is put in a queue so that its cleanup actions are executed, but the object itself is promoted to the next generation.Therefore, you have to wait until the next garbage collection that occurs on that generation (which is not necessarily the next garbage collection) to determine whether the object has been reclaimed.(http://msdn.microsoft.com/zh-cn/library/ee787088(v=vs.100).aspx)

但本人试过,用静态方法就回收不了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;


namespace ConsoleApplication2
{
    class Class1
    {
        static void Main(string[] args)
        {

            cl cll = new cl();

            of1();

            GC.Collect();

            cll.of2();

           
        }

        static void of1()
        {
            FileStream fs = new FileStream(@"C:\Documents and Settings\Administrator\桌面\dldd\aa.xls", FileMode.Open);
            SafeFileHandle aaaa = fs.SafeFileHandle;
            
            byte[] bt = new byte[10];
            fs.Read(bt, 0, 2);
            fs = null;
        }

        static void of2()
        {  
            FileStream fs = new FileStream(@"C:\Documents and Settings\Administrator\桌面\dldd\aa.xls", FileMode.Open);
            byte[] bt = new byte[10];
            fs.Read(bt, 0, 2);
        }

    }

    public class cl
    {
        public void of1()
        {
            FileStream fs = new FileStream(@"C:\Documents and Settings\Administrator\桌面\dldd\aa.xls", FileMode.Open);
            SafeFileHandle aaaa = fs.SafeFileHandle;

            byte[] bt = new byte[10];
            fs.Read(bt, 0, 2);
            fs = null;
        }

        public void of2()
        {    
            FileStream fs = new FileStream(@"C:\Documents and Settings\Administrator\桌面\dldd\aa.xls", FileMode.Open);
            byte[] bt = new byte[10];
            fs.Read(bt, 0, 2);
        }
        
    }
}
posted @ 2012-11-20 22:17  wahgon  阅读(185)  评论(0编辑  收藏  举报