Using destructors (aka finalizers) is not really a good way to do things in C #. There is no guarantee that the finalizer will work even if you explicitly call the garbage collector. You should also not try to force garbage collection, because it is likely to adversely affect your application as a whole.
Instead, if you need to explicitly free resources belonging to an object, you must implement the IDisposable interface and put your logic cleanup inside the Dispose () method. Conversely, when you use an object that implements IDisposable, you should always take care of calling the Dispose () method when you are done with it. For this purpose, C # provides a "using" statement.
Many classes that perform I / O (for example, threads) implement IDisposable. The following is an example of using FileStream to read a text file. Pay attention to the using statement to ensure that the FileStream will be deleted when we are done with it:
using (FileStream fs = File.OpenRead("C:\\temp\\myfile.txt")) { // Read a text file 1024 bytes at a time and write it to the console byte[] b = new byte[1024]; while (fs.Read(b, 0, b.Length) > 0) { Console.WriteLine(Encoding.UTF8.GetString(b)); } } // Dispose() is called automatically here
The above code is equivalent to this:
FileStream fs = File.OpenRead("C:\\temp\\myfile.txt")) try { // Read a text file 1024 bytes at a time and write it to the console byte[] b = new byte[1024]; while (fs.Read(b, 0, b.Length) > 0) { Console.WriteLine(Encoding.UTF8.GetString(b)); } } finally { fs.Dispose(); }
source share