C# 资源释放

读文件时打开时需要关闭。为了防止文件读取过程中出现异常,造成无法后续执行关闭,所以需要用try finally。

 static void Main(string[] args)
        {
            TextReader reader = new StreamReader("D:/学习/C# VS2010/第14章垃圾回收与资源管理/test.txt", Encoding.Default);
            string line;
            try
            {
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
            catch
            {
            }
            finally
            {
                reader.Close();
                //((IDisposable)reader).Dispose();//这个才是真正释放资源的方法,close也是通过调用这个。
            }  
        }

using使用方法如下,可以不用手动调用Close,在using里面的代码执行完毕后,会自动给using 括号中跟的对象执行close。

            using (TextReader reader = new StreamReader("D:/学习/C# VS2010/第14章垃圾回收与资源管理/test.txt", Encoding.Default))
            {
                string line;
                try
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
                catch
                { 
                
                }
            }

你可能感兴趣的:(C# 资源释放)