C#資源管理及IDisposable的實現(xiàn)_第1頁
C#資源管理及IDisposable的實現(xiàn)_第2頁
C#資源管理及IDisposable的實現(xiàn)_第3頁
C#資源管理及IDisposable的實現(xiàn)_第4頁
C#資源管理及IDisposable的實現(xiàn)_第5頁
已閱讀5頁,還剩8頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

1、Using of Memory (Managed and Unmanaged Resource)Zhou yuhui 2007-12-111.結(jié)論堆棧區(qū)用來存儲值數(shù)據(jù)類型,以及方法調(diào)用中的所有參數(shù)的復(fù)制。托管堆和C+中的堆不同,它用來存儲引用數(shù)據(jù)類型。GC能夠自動釋放托管資源,但是無法確定GC的調(diào)用時機GC對于OS資源無能為力, 例如文件、窗口等。.NET Framework提供了一個Object.Finalize方法,它允許在一個對象被GC要求回收它 所使用的內(nèi)存時,正確清理非托管資源。在C#中,F(xiàn)inalize即是析構(gòu)函數(shù),它的使用有損性能。Finalizer的確切執(zhí)行時間是不確定的。資源

2、不能保證在一個指定的時刻被釋放,除了 調(diào)用了 Close方法或者Dispose方法在C#中,析構(gòu)函數(shù)用來執(zhí)行清理操作。析構(gòu)函數(shù)提供了適當(dāng)?shù)谋Wo,諸如自動調(diào)用基 類的析構(gòu)函數(shù),在C#代碼中,Object.Finalize不能被調(diào)用或重寫如果使用了非托管資源,那么需要通過析構(gòu)函數(shù)來釋放資源,也可以通過實現(xiàn) IDisposable的Dispose方式顯示的釋放資源。如果使用了 expensive的非托管資源,則 推薦使用第二種方法。Dispose方法應(yīng)該釋放所有的資源,同時也要調(diào)用其基類的Dispose方法釋放其基類的 所有資源析構(gòu)函數(shù)(Finalize)中不應(yīng)該引用其他的對象,因為finalize

3、r不能以一個特定的順序 執(zhí)行。在Dispose方法中不需要主動清理托管資源,但如果是實現(xiàn)了 IDisposable的托管資源 應(yīng)該被清理,否則可能出現(xiàn)資源泄漏。要總是避免直接調(diào)用GC.Collect方法。2.相關(guān)概念C#編程的一個優(yōu)點就是程序員不需要關(guān)心具體的內(nèi)存管理,垃圾收集器會處理所有的 內(nèi)存清理工作(?)。用戶可以得到象C+語言那樣的效率,而不需要考慮象C+那樣內(nèi)存管 理的復(fù)雜性。雖然不必要手工管理內(nèi)存,但如果要編寫高效的代碼,仍需要理解后臺是如何 進行內(nèi)存管理的。在32位處理器上每個進程可以使用4GB的內(nèi)存,不管計算機有多大的硬盤空間。該 4GB空間包含程序的所有部分,可執(zhí)行代碼、代碼

4、加載的所有DLL、程序運行使用的變量 的內(nèi)存。這個4GB空間稱為虛擬地址空間,或虛擬內(nèi)存。4GB中的每個存儲單元都是從0開始往上排序的,要訪問存儲在內(nèi)存的某個空間的一 個值,就需要提供表示該存儲單元的數(shù)字。在進程的虛擬內(nèi)存中,有一個稱為堆棧的區(qū)域,它用來存儲不是對象成員的值數(shù)據(jù)類型。 另外,在方法調(diào)用時,也使用堆棧復(fù)制傳遞給方法的所有參數(shù)。堆棧指針(操作系統(tǒng)維護的 一個變量)表示堆棧中下一個自由空間的地址。程序第一次運行時,堆棧指針指向為堆棧保 留的內(nèi)存塊末尾。堆棧具有非常高的性能。托管堆是進程可用空間的另一內(nèi)存區(qū)域,它和C+使用的堆不同,它是在垃圾收集器 (Garbage Collecto

5、r)的控制下工作。它用來為引用數(shù)據(jù)類型分配空間。IDisposableIDisposable:定義一個釋放已分配的非托管資源的方法Dispose: IDisposable 的唯一公共方法,執(zhí)行與 freeing, releasing 或者 resetting 非托管 資源相關(guān)的由應(yīng)用程序定義的任務(wù)在C#中,GC(Garbage collector)會自動釋放不再使用的托管對象,但是GC的調(diào)用時機 是不能預(yù)知的。而且,GC對于例如window句柄,打開的文件或流等非托管類資源無能為 力。Dispose方法與GC共同使用可以顯示的釋放非托管資源,對象的使用者可以在該對 象不再使用的時候調(diào)用該方法釋

6、放資源。當(dāng)調(diào)用一個實現(xiàn)IDisposable接口的類時,使用try-finally模式確保即使在應(yīng)用程序有異 常發(fā)生時非托管資源仍然可以被釋放。如果客戶調(diào)用IDisposable.Dispose(),該客戶就指定應(yīng)清理所有與該對象相關(guān)的資 源,包含托管和非托管資源。如果調(diào)用了析構(gòu)函數(shù),原則上所有的資源仍需要清理。但是,析構(gòu)函數(shù)必須由GC 調(diào)用,而且不應(yīng)該訪問其他托管的對象。Garbage Collectorms-help:/MS.MSSDK.1033/MS.NETFX30SDK.1033/dv_fxadvance/html/22b6cb97-0c80-4eeb-a2cf-5ed7655e37

7、f9.htm在.NET Framework中,GC為應(yīng)用程序負(fù)責(zé)管理分配和釋放內(nèi)存。每當(dāng)使用new操作 符創(chuàng)建對象時,運行庫(runtime)就從托管堆上為對象分配內(nèi)存。只要管理堆上的地址空間是 可獲得的,運行庫就繼續(xù)為新對象分配空間。然而,內(nèi)存不是無限的,最后,GC為了釋放 內(nèi)存必須執(zhí)行回收操作。GC的優(yōu)化引擎決定了對已分配內(nèi)存執(zhí)行該操作的最佳時機。當(dāng) GC執(zhí)行一個回收操作時,它首先檢查托管堆上的對象不再被應(yīng)用程序使用,然后執(zhí)行必要 的操作回收它的內(nèi)存。這里有一個推薦的設(shè)計模式用來在你創(chuàng)建應(yīng)用程序時可以正確清除非托管資源。GC :控制系統(tǒng)垃圾回收器,一個自動回收無用內(nèi)存的服務(wù)。The met

8、hods in this class influence when garbage collection is performed on an object, and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an

9、 object.The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory ca

10、nnot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method.垃圾回收包含如下的幾個步驟:The garbage collector searches for managed objects that are referenced in managed code.The garbage collector attempts to finalize objects that are not refe

11、renced.The garbage collector frees objects that are not referenced and reclaims their memory.During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object

12、from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The KeepAlive method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code.Aside from managed me

13、mory allocations, implementations of the garbage collector do not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type can implement a fina

14、lizer.In most cases, finalizers are implemented by overriding theObject.Finalize method; however, types written in C# or C+ implement destructors, which compilers turn into an override of Object.Finalize. In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing th

15、e object. However, the garbage collector is not required to call finalizers in all situations; for example, the SuppressFinalize method explicitly prevents a finalizer from being called. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order

16、in which finalizers are called for objects that reference each other but are otherwise available for garbage collection.In scenarios where resources must be released at a specific time, classes can implement the IDisposable interface, which contains the IDisposable.Dispose method that performs resou

17、rce management and cleanup tasks. Classes that implement Dispose must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the Dispose method; however, implementations of the Dispose method can

18、call methods in the GC class to customize the finalization behavior of the garbage collector.It is recommended, but not required, that garbage collectors support object aging using generations. A generation is a unit of measure of the relative age of objects in memory. The generation number, or age,

19、 of an object indicates the generation to which an object belongs. Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. Objects in the most recent generation are in generation zero.Finalizems-help:/

20、MS.MSSDK.1033/MS.NETFX30SDK.1033/dv_fxadvance/html/fd376774-1643-499b-869e-9546a3aeea 70.htm對于應(yīng)用程序創(chuàng)建的大多數(shù)對象來說,它們需要GC隱式的執(zhí)行所有必要的內(nèi)存管理任 務(wù)。然而,當(dāng)創(chuàng)建了封裝有非托管資源的對象時,則在應(yīng)用程序使用完成后必須顯示的釋放 這些非托管資源。最常見的非托管資源類型是包含操作系統(tǒng)資源的對象,例如文件、窗口或 者網(wǎng)絡(luò)連接。雖然,GC能夠跟蹤封裝有非托管資源的對象的生命周期,但是它對于如何清 理這些資源卻無能為力。對于這些類型的對象,.NET Framework提供了一個Object

21、.Finalize 方法,它允許在一個對象被GC要求回收它所使用的內(nèi)存時,正確清理非托管資源。一般情 況下,F(xiàn)inalize什么都不作。如果需要在回收該對象內(nèi)存之前GC執(zhí)行清理操作,你必須重 寫 Finalize 方法。iNoteTo implement the Finalize method in C#, you must use destructor syntax. In the .NET Framework version 2.0, Visual C+ provides its own syntax for implementing the Finalize method, as des

22、cribed in Destructors and Finalizers in Visual C+ + . In the .NET Framework version 1.0 and 1.1, Visual C+ used destructor syntax for the Finalize method, as C# does.GC通過使用一個內(nèi)部的finalization對列來保持對實現(xiàn)Finalize方法的對象的跟蹤。在 應(yīng)用程序創(chuàng)建了 一個有Finalize方法的對象后,GC在finalization對列中存放指向該對象的 一個入口。Finalization對列包含托管堆上的所有的在G

23、C回收它們內(nèi)存之前調(diào)用它們自己的 finalization代碼的對象的入口。Finalize不能拋出異常,因為應(yīng)用程序不能處理這些異常,而且它們也會導(dǎo)致程序終止。 實現(xiàn)Finalize或者析構(gòu)函數(shù)對于性能會有負(fù)面影響,所以在不必要時要避免這么做。Reclaiming the memory used by objects with Finalize methods requires at least two garbage collections. When the garbage collector performs a collection, it reclaims the memory f

24、or inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list poin

25、t to the objects in the managed heap that are ready to have their finalization code called. The garbage collector calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbag

26、e because they are no longer pointed to by entries in the list of objects marked as ready for finalization. In this future garbage collection, the objects memory is actually reclaimed.2.3.1 Object.Finalize允許對象在被GC回收前,嘗試釋放資源以及執(zhí)行其他的清理操作。C#Object()Finalize是受保護的,它只能被該類和其繼承類訪問。除非該對象被SuppressFinalize調(diào)用免除f

27、inalization,否則該方法在一個對象不可 訪問后會被自動調(diào)用。在應(yīng)用程序關(guān)閉期間,沒有免除finalization操作的對象的Finalize 會被自動調(diào)用,即使有些對象仍然是可訪問的。Finalize在一個對象上僅僅調(diào)用一次,除 非使用諸如ReRegisterForFinalize的機制對該對象重新注冊以及隨后 GC.SuppressFinalize 沒有被調(diào)用。每一個繼承類型的Finalize實現(xiàn)必須調(diào)用其基類的Finalize的實現(xiàn)。這是一種唯一的 情況,應(yīng)用程序允許調(diào)用Finalize。Finalize有如下的限制:Finalizer的確切執(zhí)行時間是不確定的。資源不能保證在一個

28、指定的時刻被釋放, 除了調(diào)用了 Close方法或者Dispose方法兩個對象的finalizer不能保證以一個的指定的順序執(zhí)行,即使一個對象引用了另 一個對象。也就是說,如果對象A應(yīng)用了對象B,并且它們都實現(xiàn)了 finalizer, 在對象A開始finalizer時對象B可能已經(jīng)finalizer 了。Finalizer在哪個線程上運行也使不確定的在如下的異常情況下,F(xiàn)inalize方法可能不被完整執(zhí)行或者根本不能執(zhí)行:其他的finalizer無限期的阻塞(進入一個無限期的循環(huán),嘗試獲得一個不可能得 到的鎖等等)。在沒有給運行庫機會進行清理時,進城已經(jīng)終止了。這種情況下,運行苦的第一個 進程終

29、止通知是一個DLL_PROCESS_DETACH。僅僅當(dāng)finalizable對象的數(shù)量持續(xù)減少時,運行庫才會繼續(xù)在關(guān)閉期間繼續(xù)finalize 對象。如果 finalize 或者一個 finalize 的重寫拋出異常,and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try-finally blocks or finalizers are executed. This behavi

30、or ensures process integrity if the finalizer cannot free or destroy resources.實現(xiàn)的注意事項:Object.Finalize默認(rèn)什么也不做。僅在必要時,繼承類必須重寫該 方法,因為如果finalize必須執(zhí)行的話,GC的回收趨向花費更長的時間。如果一個對象持 有任何資源的引用,F(xiàn)inalize必須被繼承類重寫,用來在GC丟棄該對象之前釋放這些資源。 使用了非托管資源的類型必須實現(xiàn)Finalize,例如文件句柄、數(shù)據(jù)庫連接等非托管資源在使 用它們的對象被回收時必須被釋放。請查看IDisposable接口獲取補充的和更

31、多的處理資 源的控制方法。Finalize可以執(zhí)行任何動作,包括一個對象已經(jīng)在垃圾回收期間被清除后復(fù) 活一個對象(讓這個對象可再次訪問)。然后,這個對象僅僅能夠被復(fù)活一次;再垃圾回收期 間,復(fù)活對象的Finalize不能被調(diào)用。在C#中,析構(gòu)函數(shù)用來執(zhí)行清理操作。析構(gòu)函數(shù)提供了適當(dāng)?shù)谋Wo,諸如自動調(diào)用基 類的析構(gòu)函數(shù),在C#代碼中,ObjectFinalize不能被調(diào)用或重寫。2.4 Destructorms-help:/MS.MSSDK.1033/MS.NETFX30SDK.1033/dv_csref/html/1ae6e46d-a4b1-4a49-abe5-b97f53d9e049.htm

32、析構(gòu)函數(shù)用來銷毀類的實例。結(jié)構(gòu)體中不能定義析構(gòu)函數(shù),析構(gòu)函數(shù)僅用在類中。一個類僅能有一個析構(gòu)函數(shù)。析構(gòu)函數(shù)不能被繼承以及重載析構(gòu)函數(shù)不能被調(diào)用,是自動調(diào)用(invoke析構(gòu)函數(shù)不能有任何修飾或者參數(shù)匚#pxotectedi ovectlde vcild Finalize ()class Car/ cleanup stateiients. - Erf) / destructortlnally/ cleanup sMcenents1 析構(gòu)函數(shù)隱式的調(diào)用基類的Finalize,因此,如上圖左邊的析構(gòu)函數(shù)代碼會隱式的翻譯 成右邊的形式。對于繼承鏈上的所有實例Finalize方法會從most-deriv

33、ed到 least-derived被遞歸調(diào)用。阿注意空析構(gòu)函數(shù)不能被使用。當(dāng)一個類包含有析構(gòu)函數(shù),F(xiàn)inalize隊列會為其創(chuàng)建一個入口。 當(dāng)析構(gòu)函數(shù)被調(diào)用時,GC會被啟動來處理這個隊列。如果析構(gòu)函數(shù)是空的,這會導(dǎo)致不 必要的性能損失。程序員不能控制析構(gòu)函數(shù)的調(diào)用,它是由GC決定的。析構(gòu)函數(shù)也在程序退出時被調(diào)用。 也可以強制GC回收,但在大多數(shù)情況下不能這樣做,這會導(dǎo)致性能問題。使用析構(gòu)函數(shù)釋放資源一般來講,C#不要求太多的內(nèi)存管理,因為GC隱式的管理著內(nèi)存的分配和釋放。然 而,如果封裝了非托管資源,例如文件、窗口、網(wǎng)絡(luò)鏈接等,則必須使用析構(gòu)函數(shù)釋放這些 資源。當(dāng)一個對象成為要銷毀的對象時,G

34、C會執(zhí)行該對象的Finalize方法。顯示的釋放資源如果應(yīng)用程序使用了比較浪費(expensive)的外部資源,則推薦提供一個方法在GC釋放 該對象之前釋放這些資源。通過實現(xiàn)IDisposable的Dispose方法執(zhí)行必要的清理動作可以實 現(xiàn)顯示的釋放資源。這能夠很好的提高應(yīng)用程序的性能。即使是顯示的控制資源,析構(gòu)函數(shù) 也可以在調(diào)用Dispose失敗后清理資源。3.實現(xiàn) Disposems-help:/MS.MSSDK.1033/MS.NETFX30SDK.1033/dv_fxadvance/html/eb4e1af0-3b48-4fbc-ad 4e-fc2f64138bf9.htm根據(jù)以上

35、的調(diào)查結(jié)論,如果使用了非托管資源,那么需要通過析構(gòu)函數(shù)來釋放資源, 也可以通過實現(xiàn)IDisposable的Dispose方式顯示的釋放資源。如果使用了 expensive的非托 管資源,則推薦使用第二種方法。Dispose方法應(yīng)該釋放所有的資源,同時也要調(diào)用其基類的Dispose方法釋放其基類的 所有資源?;惖腄ispose方法也要釋放它所占用的所有資源,相應(yīng)的調(diào)用它的基類Dispose 釋放它的基類占用的資源。如此通過基類的層次結(jié)構(gòu)傳遞下去。為了保證資源總是被合適的 清理,Dispose應(yīng)該可以被調(diào)用多次且不拋出任何異常。阿重要對于C+ +的程序來講,不需要關(guān)系這個主題。相應(yīng)的,需要查看V

36、C+ +中析構(gòu)函數(shù)和 Finalizer 的內(nèi)容。在.NET Framework 2.0中,C+編譯器支持確定(deterministic) 的資源處理實現(xiàn)。而不允許直接實現(xiàn)Dispose方法。Dispose方法應(yīng)該調(diào)用GC.SuppressFinalize方法。如果對象當(dāng)前在finalization 隊列中,GC.SuppressFinalize會阻止它的Finalize方法被調(diào)用。記住Finalize的執(zhí) 行有損性能。如果Dispose方法已經(jīng)完成了對象清理工作,就沒有必要再讓GC去調(diào)用對 象的Finalize方法。1注意為System.GC.KeepAlive提供的例程表明了強制的垃圾回

37、收在一個回收對象的成員仍 然在執(zhí)行時如何引起finalizer運行的。這是一個好的做法,在冗長的Dispose方法結(jié)尾 調(diào)用 KeepAlive方法。(?)下邊的例程給出了對那些封裝有非托管資源的類實現(xiàn)Dispose方法的推薦的設(shè)計模 式。資源類一般從復(fù)雜的基本類(complex native classes)或 API繼承過來,相應(yīng)的也必 須要要定制它。使用該代碼模型作為創(chuàng)建一個資源類的開始,并基于你封裝的資源進行必要 的定制。你不能編譯下邊的例程,也不能在應(yīng)用程序中直接使用。在這個例子中,基類 BaseResource實現(xiàn)了一個公共的 Dispose方法。它調(diào)用 virtual Dispo

38、se(bool disposing)方法,參數(shù)的值依賴于調(diào)用者。在 virtual Dispose 方 法中合適的清理代碼被執(zhí)行。Dispose(bool disposing)執(zhí)行兩個不同的場景。如果參數(shù)disposing為true,該方 法被用戶代碼直接或間接的調(diào)用來處理托管和非托管的資源。如果參數(shù)disposing為false, 該方法在finalizer內(nèi)部由運行庫調(diào)用,僅僅非托管資源被處理。當(dāng)一個對象正在執(zhí)行 finalization代碼時,它不應(yīng)該引用其他的對象,因為finalizer不能以一個特定的順序執(zhí) 行。如果一個正在執(zhí)行的finalizer引用了其他已經(jīng)finalize的對象

39、,那將會失敗?;愄峁┮粋€Finalize方法(或者析構(gòu)函數(shù))作為Dispose沒有被調(diào)用的保護Finalize 方法傳遞false參數(shù)調(diào)用Dispose方法。類 MyResourceWrapper表明如何繼承于一個實現(xiàn) Dispose 的類。 MyResourceWrapper 重寫 了 virtual Dispose(bool disposing)方 法。 MyResourceWrapper也調(diào)用其基類的Dispose以確保基類可以正確的進行清理。注意, 繼承類MyResourceWrapper沒有Finalize方法、沒有參數(shù)的Dispose方法,因為它可 以從基類中繼承它們。1注意方法

40、Dispose(bool disposing)不執(zhí)行(enforce)線程安全性,因為該方法不能被一個用 戶線程以及finalizer線程同時調(diào)用。另外,一個使用BaseResource的客戶程序不能允 許多個用戶線程同時調(diào)用這個方法。一個應(yīng)用程序或類應(yīng)該被設(shè)計成僅允許一個線程擁有 一個資源的生命周期且當(dāng)資源不再使用時調(diào)用Dispose。依賴于這些資源,在資源處理時, 非同步線程的訪問會有安全風(fēng)險。開發(fā)者應(yīng)該審查它們的代碼以確定最好的執(zhí)行線程安全的方法。C#/ Design pattern for the base class./ By implementing Disposable, you

41、 are announcing that instances / of this type allocate scarce resources.public class BaseResource: Disposable / Pointer to an external unmanaged resource. private IntPtr handle;/ Other managed resource this class uses. private Component Components;/ Track whether Dispose has been called. private boo

42、l disposed = false;/ Constructor for the BaseResource object. public BaseResource() / Insert appropriate constructor code here./ Implement Disposable./ Do not make this method virtual./ A derived class should not be able to override this method. public void Dispose() Dispose(true);/ Take yourself of

43、f the Finalization queue/ to prevent finalization code for this object / from executing a second time.GC.SuppressFinalize(this);/ Dispose(bool disposing) executes in two distinct scenarios./ If disposing equals true, the method has been called directly /or indirectly by a users code. Managed and unm

44、anaged resources / can be disposed./ If disposing equals false, the method has been called by the /runtime from inside the finalizer and you should not reference / other objects. Only unmanaged resources can be tected virtual void Dispose(bool disposing) / Check to see if Dispose has alr

45、eady been called. if(!this.disposed)/ If disposing equals true, dispose all managed / and unmanaged resources.if(disposing)/ Dispose managed resources.Components.Dispose();/ Release unmanaged resources. If disposing is false, / only the following code is executed. CloseHandle(handle);handle = IntPtr

46、.Zero;/ Note that this is not thread safe./ Another thread could start disposing the object/ after the managed resources are disposed,/ but before the disposed flag is set to true./ If thread safety is necessary, it must be/ implemented by the client.disposed = true;/ Use C# destructor syntax for fi

47、nalization code./ This destructor will run only if the Dispose method/ does not get called./ It gives your base class the opportunity to finalize./ Do not provide destructors in types derived from this class.BaseResource()/ Do not re-create Dispose clean-up code here./ Calling Dispose(false) is opti

48、mal in terms of/ readability and maintainability.Dispose(false);/ Allow your Dispose method to be called multiple times, / but throw an exception if the object has been disposed. / Whenever you do something with this class, / check to see if it has been disposed.public void DoSomething() if(this.dis

49、posed) throw new ObjectDisposedException();/ Design pattern for a derived class./ Note that this derived class inherently implements the/ IDisposable interface because it is implemented in the base class. public class MyResourceWrapper: BaseResource / A managed resource that you add in this derived

50、class. private ManagedResource addedManaged;/A native unmanaged resource that you add in this derived class. private NativeResource addedNative;private bool disposed = false;/ Constructor for this object. public MyResourceWrapper() / Insert appropriate constructor code here. protected override void

51、Dispose(bool disposing) if(!this.disposed) try if(disposing) / Release the managed resources you added in / this derived class here. addedManaged.Dispose();/ Release the native unmanaged resources you added / in this derived class here. CloseHandle(addedNative); this.disposed = true; finally / Call

52、Dispose on your base class. base.Dispose(disposing); / This derived class does not have a Finalize method/ or a Dispose method without parameters because it inherits / them from the base class.實現(xiàn)Close方法For types where calling a Close method is more natural than calling a Dispose method, add a public

53、 Close method to the base type. ThdClose method in turn calls theDispose method without parameters, which performs the proper cleanup operations. The following code example illustrates a Close method.C#/ Do not make this method virtual./ A derived class should not be allowed/ to override this method

54、.public void Close()/ Calls the Dispose method without parameters.Dispose();3.1如何清理托管資源在Dispose方法中,托管資源不需要被清理。對于實現(xiàn)了 IDisposable的托管對象,還是應(yīng)該主動釋放的,否則可能有泄漏的危險。應(yīng)該總是避免直接調(diào)用GC.Collect HYPERLINK /MSDN/ShowPost.aspx?PostID=2542419&SiteID=1 /MSDN/ShowPost.aspx?PostID=2542419&SiteID=1C#public class UserProfile : IDisposableSystem.Drawing.Image _UserImage = null;public System.Drawing.Image Userimageget return _UserImage; set _UserImage = value; private string _UserName = string.Empty;public string UserName

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論