When to dispose and why?

后端 未结 12 1067
臣服心动
臣服心动 2020-12-10 14:20

I asked a question about this method:

// Save an object out to the disk
public static void SerializeObject(this T toSerialize, String filename)
{
           


        
12条回答
  •  一个人的身影
    2020-12-10 14:31

    Well actually you already are disposing it since the textWriter.Close Method does it.

    public virtual void Close()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }
    

    So you could change your code to. This

    public static void SerializeObject(this T toSerialize, String filename)
    {
        TextWriter textWriter;
        try
        {
             XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
             textWriter = new StreamWriter(filename);
    
              xmlSerializer.Serialize(textWriter, toSerialize);
        }
        finally
       {
           textWriter.Close();
       }
    

    Which is pretty similar to what the using() does in the other answers.

    The impact of not doing this is that if an error occurs with Serialize it would be a while before the Framework gave up its file lock (when it Processes the fReachable queue).

    I know FxCop tells you when to implment IDisposable but I don't think there's any easy way to find out when you need to call Dispose other than looking at the Docs and seeing if an object implments IDisposable (or intellisense).

提交回复
热议问题