Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c# - When does File.ReadLines free resources

When working with files in C#, I am conditioned to think about freeing the associated resources. Usually this is a using statement, unless its a one liner convenience method like File.ReadAllLines, which will open and close the file for me.

.Net 4.0 has introduced the convenience method File.ReadLines. This returns an IEnumerable and is billed as a more efficient way to process a file - it avoids storing the entire file in memory. To do this I'm assuming there is some deferred execution logic in the enumerator.

Obviously since this method returns an IEnumerable, not and IDisposable, I can't go with my gut reaction of a using statement.

My questions is: With this in mind, are there any gotchas on resource deallocation with this method?

Does calling this method mean that the release of the associated file locks is non-deterministic?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

IEnumerable doesn't inherit from IDisposable because typically, the class that implements it only gives you the promise of being enumerable, it hasn't actually done anything yet that warrants disposal.

However, when you enumerate over it, you first retrieve an IEnumerator by calling the IEnumerable.GetEnumerator method, and typically, the underlying object you get back does implement IDisposable.

The way foreach is implemented is similar to this:

var enumerator = enumerable.GetEnumerator();
try
{
    // enumerate
}
finally
{
    IDisposable disposable = enumerator as IDisposable;
    if (disposable != null)
        disposable.Dispose();
}

This way, if the object does indeed implement IDisposable, it will be disposed of. For File.ReadLines, the file isn't really opened until you start enumerating over it, so the object you get from File.ReadLines doesn't need disposing, but the enumerator you get, does.

As the comments indicate, IEnumerator does not inherit from IDisposable, even though many typical implementations does, whereas the generic IEnumerator<T> does inherit IDisposable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...