numerable扩展是否在其IEnumerable上调用了Di

numerable扩展是否在其IEnumerable上调用了Di

本文介绍了LINQ IEnumerable扩展是否在其IEnumerable上调用了Dispose?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我已经编写了一个实现IEnumerable的类,并返回了一个IEnumerator,它不仅是枚举器,而且还具有IDisposable的性质,它是从管理完成后需要的资源到Dispose()枚举,只要我的枚举器在其IDisposable实现中正确配置了这些托管资源,我是否可以相信以下内容将对这些托管资源进行Dispose()?

Given I've written a class that implements IEnumerable, and returns an IEnumerator that's not just IDisposable by nature of being an enumerator, but from having managed resources that it needs to Dispose() after it's done enumerating, can I trust that the following will Dispose() those managed resources as long as my enumerator properly disposes those managed resources in its IDisposable implementation?

return (new MyClass()).Select(x => x);

这个问题似乎类似于标记为类似问题的那个mod,但是它在语义上是不同的IMO(我在提出问题之前就已经看到了它)

This question is seemingly similar to the one mods marked similar to it, but it's semantically different IMO (I saw it before I made the question)

推荐答案

是的,您可以在LINQ的方法中依靠迭代器上的Dispose()调用.

Yes, you can rely on the call of Dispose() on your iterators from inside the methods of LINQ.

在Microsoft发布的参考代码中,使用了迭代器分为三类:

In the reference code published by Microsoft, the use of iterators falls in three categories:

    foreach循环中使用
  • 迭代器,以确保调用Dispose()
  • 迭代器与while循环一起使用;这些迭代器已明确处理
  • 迭代器在using块内获取,可确保自动处理.
  • Iterators are used from within a foreach loop, which ensures a call of Dispose(), or
  • Iterators are used in conjunction with a while loop; these iterators are disposed explicitly
  • Iterators are obtained inside a using block, which ensures automatic disposal.

在所有这些情况下,库都确保在完成时调用迭代器的Dispose()方法.

In all these cases the library ensures that iterator's Dispose() method is called upon completion.

这篇关于LINQ IEnumerable扩展是否在其IEnumerable上调用了Dispose?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:03