關於非託管資源GDI對象泄漏-解決問題隨筆

要在一個龐雜的系統之中找到非託管資源泄漏的位置,是一個極爲頭痛的事情,所以在託管平臺操作非託管資源一定要謹慎,用完便要及時釋放,否則埋下的雷,過一段時間要費極大的代價和心力去找。更別提是要在別人雜亂的代碼之中去找這顆雷了,就像我這次一樣,都要累吐了。還好找到一個監測非託管資源句柄的工具,英文的,粗略的把程序漢化了一下,有想用的可以下載,這個是目前爲止最新的版本。

*************************************

更新,遺憾的是,用該工具並未監測到常規GDI對象的泄漏情況,但卻監測到總佔用GDI節節攀升:

看了一下該工具作者的描述,他這樣寫道:

'GDI Total' and 'All GDI' columns

The 'GDI Total' column (a new column added on v1.05) displays the total number of all GDI handles found in the GDI table for the specified process. This means that 'GDI Total' column display the sum of the following columns: Pen, ExtPen, Brush, Bitmap, Font, Palette, Region, DC, Metafile DC, Enhanced Metafile DC, and Other GDI.
The 'All GDI' value is taken from Windows API call (GetGuiResources), and it usually contains a value larger than 'GDI Total', probably because it also counts some internal kernel GDI objects that are not included in the GDI objects table of the process.

Notice: If you have a problem that the 'All GDI' value is increased, while there is no leak with the other GDI values, it means that you probably have a leak in the creation of icons or cursors (Icons and cursors are created without destroying them later).

另外經過查閱相關資料,得知對於非託管資源GDI對象的創建和釋放,一般由以下幾種方法來執行:

Create出來的GDI對象,都要用DeleteObject來釋放;Create出來的DC,都要用DeleteDC來釋放,GetDC得出的DC,要用ReleaseDC來釋放。

唉……接着找吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章