关于释放byte[]内存
有人说过,值类型存在堆栈上,不用的时侯就自动释放。
可我今天遇到这种情况很奇怪,byte[]执行GC.Collect();才能释放内存,否则一直占用内存。
先说一下我主要的目的:将本地本文件用webservice方式上传至服务器
代码如下:
public byte[] ReadBytes(string path) { FileStream fs = null;//= new FileStream(path, FileMode.Open, FileAccess.Read); byte[] data=null; BinaryReader r = null;// new BinaryReader(fs); try { using (fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { using (r = new BinaryReader(fs)) { data = r.ReadBytes((int)fs.Length); } } } catch (Exception ex) { throw ex; } finally { if (fs!=null) { fs.Close(); fs.Dispose(); } if (r != null) { r.Close(); } } return data; } public bool PutFile(byte[] buffer, string filepath) { bool isSuc = false; if (File.Exists(filepath)) { File.Delete(filepath); } BinaryWriter binWriter =null; try { using (binWriter = new BinaryWriter(File.Open(filepath, FileMode.CreateNew, FileAccess.ReadWrite))) { binWriter.Write(buffer); binWriter.Flush(); } isSuc = true; } catch (Exception ex) { isSuc = false; throw ex; } finally { if (binWriter!=null) { binWriter.Close(); } GC.Collect(); //GC.Collect(3, GCCollectionMode.Optimized); } //有此句GC不会回收,无此句GC会回收 //int length = buffer.Length; return isSuc; }