开发者

How to use IDisposable on my custom class?

Here is what I have:

public void FindByID(string id)
{
    using (Parser parser = new Parser()) {
        if ( parser.LoadUserById(id)) {
            ID = parser.FindID();
            Name = parser.FindName();
            // ...
        }
        else {
            MessageBox.Show("User not found.");
        }
    } // end using block.开发者_如何学Python parser is disposed so its memory is free to use again. 
}

And here is the actual Parser class itself:

public class Parser : IDisposable
{                
    XDocument doc;
    bool userExists = true;
    private const string xmlInformationAddress = 
            "http://www.dreamincode.net/forums/xml.php?showuser={0}";

    public bool LoadUserById(string userID)
    {
        try
        {
            doc = XDocument.Load(String.Format(xmlInformationAddress, userID));

            if (doc.Root.Elements().Any())
            {
                userExists = true;
                return true;
            }
            else 
            {
                userExists = false;                
                return false;
            }
        }
        catch (Exception e)
        {
            doc = new XDocument();
            userExists = false;
            return false;
        }
    }
}

It says I'm not implementing the Dispose() method, but I'm not sure what is supposed to go inside of that method.


Well, why do you want to implement IDisposable? If you've got nothing to dispose of (which looks like it's the case here) then clients shouldn't have to call Dispose.

You seem to be under the impression that calling Dispose will free the memory taken by the object. That's the garbage collector's job - Dipose is entirely separate. It's designed to release unmanaged resources such as file handles (including those indirectly held, such as references to Streams).

In this case:

  • Don't implement IDisposable
  • Get rid of the using statement in your calling code
  • Trust the GC :)


Your class doesn't seem like it needs to implement IDisposable. That being said, if you want to understand how and why you would implement it, you could read my series on IDisposable. It goes into how and why (and when) you should implement IDisposable in detail.

In this case, you have no reason to use IDisposable, since your object doesn't hold any native resources. If it used native resources, or encapsulated another class that implemented IDisposable, then, and only then, you should implement IDisposable.

That being said, IDisposable has nothing to do with freeing memory - that's the job of the GC. It's about freeing resources, which can include memory (allocated natively), but more often involves native handles and other resources.


I agree with Jon Skeet. But if you did have something to "dispose" of -

var x = new Parser();
using (x) {
   // Do stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜