Home Backend Development C#.Net Tutorial .Net 的 IDisposable interface

.Net 的 IDisposable interface

Nov 21, 2016 pm 02:54 PM

The Garbage Collection in the .Net Framework will help programmers automatically recycle managed resources. This is a very pleasant experience for the callers of the class library: any object can be created at any location and at any time, and the GC will always eventually reveal all the details. How can we provide such a good experience when we are a class library provider?

First of all, which resources are managed and which are unmanaged resources in .Net framework?

Basically, all classes in the .Net framework are managed resources, including various streams (such as FileStream, MemoryStream), database connection, components, etc. .

You can write a simple small program to verify: (take FileStream as an example)

A method to monitor whether the file is being occupied in the background thread:

        private static void MonitorFileStatus(string fileName)
        {
            Console.WriteLine("Start to monitor file: {0}", fileName);
            Task.Factory.StartNew(() =>
            {
                while(true)
                {
                    bool isInUse = IsFileInUse(fileName);

                    string messageFormat = isInUse ? "File {0} is in use." : "File {0} is released.";
                    Console.WriteLine(messageFormat, fileName);
                    Thread.Sleep(oneSeconds);
                }
            });
        }


        private static bool IsFileInUse(string fileName)
        {
            bool isInUse = true;
            FileStream stream = null;
            try
            {
                stream = File.Open(fileName, FileMode.Append, FileAccess.Write);
                isInUse = false;
            }
            catch
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
            return isInUse;
        }
Copy after login

Write another method that occupies the file when it is not used, FileStream is just a partial Variable, when this method returns, it should be recycled:

        private static void OpenFile()
        {
            FileStream stream  = File.Open(TestFileName, FileMode.Append, FileAccess.Write);
            Wait(fiveSeconds);
        }
Copy after login

Finally, there is an essential wait:

        private static void Wait(TimeSpan time)
        {
            Console.WriteLine("Wait for {0} seconds...", time.TotalSeconds);
            Thread.Sleep(time);
        }
Copy after login

Combined, it is a test:
First start the file monitoring thread, and then open the file.
The OpenFile method returns, predicting that the FileStream will be recycled
Then call the GC to see if the file has been released

        private static void FileTest()
        {
            MonitorFileStatus(TestFileName);

            OpenFile();

            CallGC();
            Wait(fiveSeconds);
        }
Copy after login

The running results show that the GC automatically recycles the FileStream. There is no need to call the Dispose method or use using

.Net 的 IDisposable interface

So, what do unmanaged resources include?

Usually, when it comes to Windows API pinvoke, various intptr are unmanaged resources. For example, if you open a file as follows, it includes unmanaged resources

    [Flags]
    internal enum OpenFileStyle : uint
    {
        OF_CANCEL = 0x00000800,  // Ignored. For a dialog box with a Cancel button, use OF_PROMPT.
        OF_CREATE = 0x00001000,  // Creates a new file. If file exists, it is truncated to zero (0) length.
        OF_DELETE = 0x00000200,  // Deletes a file.
        OF_EXIST = 0x00004000,  // Opens a file and then closes it. Used to test that a file exists
        OF_PARSE = 0x00000100,  // Fills the OFSTRUCT structure, but does not do anything else.
        OF_PROMPT = 0x00002000,  // Displays a dialog box if a requested file does not exist 
        OF_READ = 0x00000000,  // Opens a file for reading only.
        OF_READWRITE = 0x00000002,  // Opens a file with read/write permissions.
        OF_REOPEN = 0x00008000,  // Opens a file by using information in the reopen buffer.

        // For MS-DOS–based file systems, opens a file with compatibility mode, allows any process on a 
        // specified computer to open the file any number of times.
        // Other efforts to open a file with other sharing modes fail. This flag is mapped to the 
        // FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function.
        OF_SHARE_COMPAT = 0x00000000,

        // Opens a file without denying read or write access to other processes.
        // On MS-DOS-based file systems, if the file has been opened in compatibility mode
        // by any other process, the function fails.
        // This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function.
        OF_SHARE_DENY_NONE = 0x00000040,

        // Opens a file and denies read access to other processes.
        // On MS-DOS-based file systems, if the file has been opened in compatibility mode,
        // or for read access by any other process, the function fails.
        // This flag is mapped to the FILE_SHARE_WRITE flag of the CreateFile function.
        OF_SHARE_DENY_READ = 0x00000030,

        // Opens a file and denies write access to other processes.
        // On MS-DOS-based file systems, if a file has been opened in compatibility mode,
        // or for write access by any other process, the function fails.
        // This flag is mapped to the FILE_SHARE_READ flag of the CreateFile function.
        OF_SHARE_DENY_WRITE = 0x00000020,

        // Opens a file with exclusive mode, and denies both read/write access to other processes.
        // If a file has been opened in any other mode for read/write access, even by the current process,
        // the function fails.
        OF_SHARE_EXCLUSIVE = 0x00000010,

        // Verifies that the date and time of a file are the same as when it was opened previously.
        // This is useful as an extra check for read-only files.
        OF_VERIFY = 0x00000400,

        // Opens a file for write access only.
        OF_WRITE = 0x00000001
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct OFSTRUCT
    {
        public byte cBytes;
        public byte fFixedDisc;
        public UInt16 nErrCode;
        public UInt16 Reserved1;
        public UInt16 Reserved2;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
        public string szPathName;
    }

    class WindowsApi
    {
        [DllImport("kernel32.dll", BestFitMapping = false, ThrowOnUnmappableChar = true)]
        internal static extern IntPtr OpenFile([MarshalAs(UnmanagedType.LPStr)]string lpFileName, out OFSTRUCT lpReOpenBuff, OpenFileStyle uStyle);

        [DllImport("kernel32.dll", SetLastError = true)]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool CloseHandle(IntPtr hObject);
    }
Copy after login

To handle unmanaged resources, you need to implement the IDisposable interface. There are two reasons:

You cannot rely on destructors, because the call of heterogeneous functions is determined by the GC. Scarce resources cannot be released in real time.

There is a general processing principle: destructor handles managed resources, and IDisposable interface handles managed and unmanaged resources.

As in the above example, the completed implementation code is as follows:

    public class UnmanagedFileHolder : IFileHolder, IDisposable
    {
        private IntPtr _handle;
        private string _fileName;

        public UnmanagedFileHolder(string fileName)
        {
            _fileName = fileName;
        }

        public void OpenFile()
        {
            Console.WriteLine("Open file with windows api.");
            OFSTRUCT info;
            _handle = WindowsApi.OpenFile(_fileName, out info, OpenFileStyle.OF_READWRITE);
        }

        #region IDisposable Support
        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // no managed resource
                }
                WindowsApi.CloseHandle(_handle);
                _handle = IntPtr.Zero;

                disposed = true;
            }
        }

        ~UnmanagedFileHolder()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
Copy after login

What should we do if there are both managed resources and unmanaged resources in the same class?

You can follow the following pattern:

    class HybridPattern : IDisposable
    {
        private bool _disposed = false;

        ~HybridPattern()
        {
            Dispose(false);
        }

        protected void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                // Code to dispose the managed resources of the class
                // internalComponent1.Dispose();
            }

            // Code to dispose the un-managed resources of the class
            // CloseHandle(handle);
            // handle = IntPtr.Zero;

            _disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
Copy after login

The following is a complete example, with managed FileStream, and unmanaged Handler

    public class HybridHolder : IFileHolder, IDisposable
    {
        private string _unmanagedFile;
        private string _managedFile;

        private IntPtr _handle;
        private FileStream _stream;

        public HybridHolder(string unmanagedFile, string managedFile)
        {
            _unmanagedFile = unmanagedFile;
            _managedFile = managedFile;
        }

        public void OpenFile()
        {
            Console.WriteLine("Open file with windows api.");
            OFSTRUCT info;
            _handle = WindowsApi.OpenFile(_unmanagedFile, out info, OpenFileStyle.OF_READWRITE);

            Console.WriteLine("Open file with .Net libray.");
            _stream = File.Open(_managedFile, FileMode.Append, FileAccess.Write);
        }

        #region IDisposable Support
        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                //Console.WriteLine("string is null? {0}", _stream == null);
                if (disposing && _stream != null)
                {
                    Console.WriteLine("Clean up managed resource.");
                    _stream.Dispose();
                }

                Console.WriteLine("Clean up unmanaged resource.");
                WindowsApi.CloseHandle(_handle);
                _handle = IntPtr.Zero;

                disposed = true;
            }
        }

        ~HybridHolder()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
Copy after login

Finally, what if it is a class that does not implement IDisposable interface? For example, byte[], StringBuilder

don't interfere with their recycling at all, GC does a good job.
I tried setting a huge byte[] to null in the destructor. The only result was that its collection was delayed until the next GC cycle.
The reason is also very simple. Each time a reference is made, the count on its reference tree will be increased by one. .

See Github for the complete code:

https://github.com/IGabriel/IDisposableSample


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Apr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

Is C# .NET Right for You? Evaluating its Applicability Is C# .NET Right for You? Evaluating its Applicability Apr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming Process C# Code within .NET: Exploring the Programming Process Apr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET and the Future: Adapting to New Technologies C# .NET and the Future: Adapting to New Technologies Apr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

See all articles