C#内存泄漏的事例
一,使用非托管资源忘记及时Dispose
(1) 使用完非托管资源一定要Dispose或者使用using
1using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) 2 { 3 string str = "我好像不能全部覆盖源文件中的数据"; 4 byte[] buffer = Encoding.Default.GetBytes(str); 5 fsWrite.Write(buffer,0,buffer.Length);//无返回值,以字节数组的形式写入数据 6 } 7 8 string path =@"C:\Users\fighting man\Desktop\FileStream的使用\vs快捷键.txt" ; 9 FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read); 10 //三个参数(参数1读取文件的路径,参数2对文件的做什么样的操作,参数3对文件中的数据做什么样的操作) 11 //FileStream 用来操作字节(不是一次性读取对内存压力小适合读大文件) 12 try 13 { 14 //创建FileStream类的对象(路径,对文件的操作,对文本文件数据的操作) 15 byte[] buffer = new byte[1024 * 1024 * 1]; 16 int r = fsRead.Read(buffer, 0, buffer.Length);//把数据读到字节数组中,返回实际读到的有效字节数 17 string str = Encoding.Default.GetString(buffer, 0, r);//解码到实际读到的字节数 18 } 19 finally 20 { 21 fsRead.Close();//关闭流 22 fsRead.Dispose();//释放流 23 }
非托管资源还包括OracleConnection,套接字,com对象,操作excel对象等,使用完毕一定要手动Dispose。
(2)定义的自定义类里使用了非托管资源,需要继承接口IDisposable,实现Dispose方法,手动清理掉内部非托管资源。
1public class DealData : IDisposable 2 { 3 private bool disposed = false; 4 5 private System.Timers.Timer t = new System.Timers.Timer(); 6 7 private List<object> listAll; 8 9 public void Dispose() 10 { 11 Dispose(true); 12 GC.SuppressFinalize(this); 13 } 14 15 protected virtual void Dispose(bool disposing) 16 { 17 if (!disposed) 18 { 19 if (disposing) 20 { 21 listAll.Clear(); 22 //释放托管资源 23 } 24 t.Dispose(); 25 //释放非托管资源 26 disposed = true; 27 } 28 } 29 30 ~DealData() { 31 MessageBox.Show("析构函数"); 32 } 33 }
二,静态引起的内存泄漏现象
(1)静态对象导致的内存堆积,程序不执行完毕,内存就不能释放
1public class MySingletonClass 2{ 3 private static MySingletonClass myInstance; 4 private static List<IAmBig> bigObjects = new List<IAmBig>(); 5 private MySingletonClass(){} 6 public static MySingletonClass MyInstance 7 { 8 get 9 { 10 if(myInstance == null) 11 { 12 myInstance = new MySingletonClass(); 13 } 14 return myInstance; 15 } 16 } 17 public static IAmBig CreateBigObject() 18 { 19 var bigObject = new IAmBig(); 20 bigobject.AllocateMemory(4096); 21 bigObjects.add(bigObject); 22 return bigObject; 23 } 24} 25public class IAmBig 26{ 27 28}