6
我曾經認爲在使用Assembly.GetManifestResourceStream
方法訪問嵌入式裝配資源時,最好在完成之後關閉返回的Stream
。不過,我只是發現了下面的文章中的內容:我應該關閉由Assembly.GetManifestResourceStream返回的流嗎?
http://msdn.microsoft.com/en-us/library/ms950960.aspx
// Get the stream that holds the resource
// NOTE1: Make sure not to close this stream!
// NOTE2: Also be very careful to match the case
// on the resource name itself
Stream stream =
assem.GetManifestResourceStream("Azul.jpg");
// Load the bitmap from the stream
this.BackgroundImage = new Bitmap(stream);
的評論在這裏說,該流應該不被關閉,雖然文章沒有提到的原因。谷歌搜索沒有提供任何結論;有些人似乎關閉了這個流,其他人不會說垃圾回收器會處理它。
我應該關閉由Assembly.GetManifestResourceStream
返回的流嗎?有沒有特別的原因,我不應該?
它確實繼續從它創建一個位圖,但爲什麼在創建位圖之後仍然沒有關閉它? – Jez 2012-08-10 17:15:38
該示例將Bitmap用作Windows窗體的背景圖像,因此在整個窗體生命週期中都需要Bitmap(和基礎流)。不幸的是,這不是一個很好的示例,顯示如何正確管理IDisposable對象。 – 2012-08-10 17:21:07