文章;MemoryStream.Close() or MemoryStream.Dispose()

Close() and Dispose(), when called on a MemoryStream, only serve to do two things:

  • Mark the object disposed so that future accidental usage of the object will throw an exception.
  • Possibly1 release references to managed objects, which can make the GC's job a bit easier depending on the GC implementation. (On today's GC algorithms it makes no real difference, so this is a point for an academic discussion and has no significant real-world impact.)

MemoryStream does not have any unmanaged resources to dispose, so you don't technically have to dispose of it. The effect of not disposing a MemoryStream is roughly the same thing as dropping a reference to a byte[] -- the GC will clean both up the same way.

Which one do I call? Is it necessary to call both?

The Dispose() method of streams delegate directly to the Close() method2, so both do exactly the same thing.

Will the other throw an exception if I have already called one of them?

The documentation for IDisposable.Dispose() specifically states it is safe to call Dispose() multiple times, on any object3. (If that is not true for a particular class then that class implements the IDisposable interface in a way that violates its contract, and this would be a bug.)

All that to say: it really doesn't make a huge difference whether you dispose a MemoryStream or not. The only real reason it has Close/Dispose methods is because it inherits from Stream, which requires those methods as part of its contract to support streams that do have unmanaged resources (such as file or socket descriptors).

最新文章

  1. MTK 常见的编译命令
  2. 【AdaBoost算法】弱分类器训练过程
  3. SAP增强总结-第二代增强(SMOD、CMOD)【转载】
  4. [转]CSS 模块
  5. Android的十六进制颜色值
  6. .net 使用AjaxControlToolkit.dll 遇到的"Sys"未定义问题
  7. JS删除练习
  8. Windows PowerShell 简介
  9. C++ Primer 学习笔记_54_类和数据抽象 --拷贝构造函数、赋值运算符
  10. install webapp2 on Linux outside google app engine.
  11. C++STL的简单使用
  12. Orleans部署
  13. mysql 数据库复制方法
  14. Shuffle(洗牌)
  15. 【IT笔试面试题整理】数组中出现次数超过一半的数字
  16. 编译java代码出现 错误: 需要class, interface或enum 提示
  17. unity3d之 C# WaitFOrSeconds()
  18. HBase TableExistsException: hbase:namespace
  19. Oracle 11g 新特性 -- Oracle Restart 说明(转载)
  20. 好记性不如烂笔头-linux学习笔记6keepalived实现主备操作

热门文章

  1. Visual Studio + Qt:GetVarsFromMakefile任务意外失败
  2. Vue组件注册与数据传递
  3. maven的依赖范围scope
  4. vim设定Tab缩进长度
  5. Java课堂笔记1
  6. 【剑指offer】数组在排序数组中出现的次数
  7. C++ 智能指针 std::auto_ptr 分析
  8. SQL Server 中关于系统库Tempdb总结
  9. Java学习笔记——线程
  10. C++ 工程师养成 每日一题4.5 (迭代器遍历)