Содержание
- 2. Agenda Destructor and Finalizer in C# IDisposable and RAII Dispose Pattern for Managed and Unmanaged Resources
- 3. Destructor and Finalizer in C#
- 4. Destructor in C# Destructor in C# language created with tilde (“~”) is syntax sugar for Finalize
- 5. Finalizer Problem Time of finalizer call is not defined in .NET, that is why finalizers do
- 6. IDisposable and RAII
- 7. Interface IDisposable Provides a mechanism for releasing unmanaged resources.
- 8. RAII Idiom RAII – Resource Acquisition Is Initialization RAII means that resource should be allocated in
- 9. Keyword using Keyword “using” not completely implements RAII // Opening file inside using block using (FileStream
- 10. Method Dispose Dispose method differs from destructor in that way that it not destroys the object
- 11. Dispose Pattern for Managed and Unmanaged Resources
- 12. Dispose Pattern Taking into account all previously mentioned, we have to implement special dispose pattern in
- 13. Managed and Unmanaged Resources Unmanaged resources – IntPtr, socket descriptors, any OS objects obtained with WinAPI
- 14. Sample Resource Wrapper class NativeResourceWrapper : IDisposable { // IntPtr – unmanaged resource descriptor private IntPtr
- 15. Main Idea of Dispose Pattern The main idea of Dispose Pattern is: Place all logic of
- 16. 1. Interface Implementation Class that has both managed and unmanaged resources implements IDisposable interface class Boo
- 17. 2. Method Dispose(bool disposing) Class contains method Dispose(bool disposing) that does all job to release resources;
- 18. 3. Method Dispose() Dispose method implementation: first we call Dispose(true), then we may call GC.SuppressFinalize() method
- 19. Notes to GC.SupressFinalize() Call GC.SuppressFinalize() should be called after Dispose(true) but not before because if method
- 20. 4. Parameter “disposing” Method Dispose(bool disposing) has two parts: If this method called from Dispose (disposing
- 21. 5. Finalizer [OPTIONAL] Class may have finalizer and call Dispose(bool disposing) from it passing false as
- 22. 6. Field “disposed” The good practice is to create special Boolean field disposed which indicates that
- 23. Objects with Critical Finalization
- 24. 7. Object with Critical Finalization Class may be inherited from CriticalFinalizerObject: Finalizer for such classes compiled
- 25. Simplified Dispose Pattern
- 26. Simplifying Dispose Pattern Most difficulties with Dispose pattern implementation based on assumption that same class (or
- 27. Simplified Dispose Pattern Used only for managed resources class SomethingWithManagedResources : IDisposable { public void Dispose()
- 28. Recommended Links
- 30. Скачать презентацию