hhhh2010

博客园 首页 新随笔 联系 订阅 管理

      今天偶然使用VS代码分析,发现CA2000警告,然后其中一条为streamWriter、streamReader与FileStream相关内容,特查询并记录一下。

      引文地址:http://bbs.csdn.net/topics/390313584;

        http://blog.csdn.net/jaychouliyu/article/details/6152256

        实现代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
            //StreamReader sr = new StreamReader(fs);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write("Hi there");
            //注意:调用StreamWriter.Close会同时关闭其使用的FileStream对象,而FileStream对象不需要显示地关闭  
            //sw.Close();
            sw.Dispose();
            fs.Dispose();
            
            Thread.Sleep(4000);
            if(sw == null)
            {
                Console.WriteLine("Null");
            }
            else
            {
                Console.WriteLine("not Null");
            }
            Console.ReadLine();
        }
    }
}

        先释放“sw”后释放“fs”时,确实会出现“对象未按所有异常路径释放”;如果先释放“fs”,后释放“sw”,出现“ObjectDisposeException”。“fs”与“sw”的确是互相关联,释放其中一个,会对另外一个造成一定的影响,

posted on 2016-02-23 16:13  hhhh2010  阅读(305)  评论(0编辑  收藏  举报