问题描述
当在C#文件时,我条件反射地想释放相关资源。通常这是一个using语句,除非它是一个单行的简便方法像File.ReadAllLines,这将打开和关闭文件给我。
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 methodlike File.ReadAllLines, which will open and close the file for me.
.NET 4.0中引入了方便的方法File.ReadLines。这将返回IEnumerable和被标榜为处理一个文件,一个更有效的方法 - 它避免了在内存中存储的全部文件。要做到这一点,我假设有一个在枚举一些延迟执行的逻辑。
.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.
显然,因为这种方法会返回一个IEnumerable,而不是和IDisposable的,我不能去同一个using语句我的直觉反应。
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?
推荐答案
的IEnumerable
不自IDisposable继承,因为通常情况下,实现它的类只让你的诺的被枚举,它实际上并没有做任何事情权证处置。
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.
然而,当您列举了它,你先检索的IEnumerator
致电 IEnumerable.GetEnumerator
的方法,而通常情况下,你回来了基础对象的确实的实施的IDisposable
。
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
.
方式的foreach
的实施与此类似:
var enumerator = enumerable.GetEnumerator();
try
{
// enumerate
}
finally
{
IDisposable disposable = enumerator as IDisposable;
if (disposable != null)
disposable.Dispose();
}
这样一来,如果对象确实落实的IDisposable
,它会被处理掉。对于 File.ReadLines
,该文件是不是真的开了,直到你开始列举了它,所以对象从 File.ReadLines $得到C $ C>不需要处理,但你的枚举,确实。
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.
作为评论表明,的IEnumerator
不从的IDisposable
继承,尽管许多典型的实现呢,而通用的IEnumerator< T>
并继承的IDisposable
As the comments indicate, IEnumerator
does not inherit from IDisposable
, even though many typical implementations does, whereas the generic IEnumerator<T>
does inherit IDisposable
.
这篇关于什么时候File.ReadLines免费资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!