2011-11-15 24 views
2

難道這還不夠:在表達式中創建的圖像是否立即生成?

using (Graphics g = Graphics.FromImage(image)) 
    { 
     g.DrawImage(newImage.GetThumbnailImage(10, 10, null, new IntPtr()), 3, 3, 10, 10); 
    } 

或者我應該使用:

using (Graphics g = Graphics.FromImage(image)) 
     { 
      using (Image i = newImage.GetThumbnailImage(10, 10, null, new IntPtr())) 
      { 
       g.DrawImage(i, 3, 3, 10, 10); 
      } 
     } 

編輯: 可有人請添加一些MS參考,即使是沒有創建的變量 - 的資源不會被釋放立即?

回答

2

這是不會被處置,除非你特別呼籲Dispose()方法(或離開using塊)。所以在你的情況下,使用第二個using塊是確保你釋放非託管資源的更安全的選擇。

2

對於實現IDisposable的類型,您應該使用using語句。否則,資源不會被釋放,直到對象完成。

爲了使代碼一點點整潔,我喜歡堆棧using

using (Graphics g = Graphics.FromImage(image)) 
    using (Image i = newImage.GetThumbnailImage(10, 10, null, new IntPtr())) 
    { 
     g.DrawImage(i, 3, 3, 10, 10); 
    } 
1

不僅將垃圾收集不immediatelly觸發,但如果他們持有的系統資源可能無法正確清除的對象 - 如文件。雖然我不確定Image類,但是,如果您的代碼必須(有一天)在緊張的內存中運行,您需要在完成後立即清理圖像。這是usingIDisposable進來

我發現了一個很不錯的博客曾經對使用塊here,下面的代碼:

using (MyClass myClass = GetMyClass()) 
{ 
    myClass.DoSomething(); 
} 

的行爲完全是這樣的:

MyClass myClass = GetMyClass(); 
try 
{ 
    myClass.DoSomething(); 
} 
finally 
{ 
    IDisposable disposable = myClass as IDisposable; 
    if (disposable != null) disposable.Dispose(); 
} 

所以即使你的代碼拋出和異常,也會清理你的Image,如果你自己調用dispose,它將不會引起任何問題。

簡而言之:總是使用與實現IDisposable的對象一起使用,此外,如果代碼複雜,請在您不再需要該對象時立即釋放 - 並將對象引用設置爲null。

相關問題