Yielding with an IDisposable resource

浪子不回头ぞ 提交于 2019-12-12 10:33:10

问题


Is there a proper way to yield through a disposable resource? The returned objects are IDisposable, but the element it is iterating through is.

Here is an example:

public static IEnumerable<T> Fetch(IEnumerable<Guid> ids)
{
    using (var client = new CouchbaseClient())
    {
        yield return ids.Select(s => s.ToString());
    }
}

Right now, calling this would not dispose the using resource obtained. I know I can just to a ToList and return it all at once, but is there a way to handle this "properly", or do I have to keep a tab on the IDisposable resource and dispose of it manually when I'm done?


回答1:


In short, you don't need to worry about it as long as the caller of the method handles the IEnumerator objects properly.

IEnumerator implementes IDisposable, and the logic used in creating the iterator blocks is actually smart enough to execute all un-executed finally blocks when it is disposed. A finally block is created as a result of the using call, and that is where the IDisposable resource is disposed.

So as long as the IEnumerator objects created from this IEnumerable are either iterated fully (in which case the final MoveNext call will reach the end of the using block and dispose of the resource) or disposed the IDisposable client will be disposed.

Note that if you're concerned the user of your code may not treat the IEnumerator objects properly then you're best bet is to not use an iterator block with lazy evaluation. If you want to ensure that even if the caller doesn't "play nice" then eagerly evaluate the method (i.e. take the code you have, dump the results into a list, and then return that list). If the consequences of not disposing the resource are primarily, or entirely performance related (not releasing some memory for a while longer, keeping open a connection, etc.) then it may not be a concern, but if holding onto the lock forever is a major problem (i.e. a locked resource that could result in deadlocks if not released) then the advantage of lazy evaluation may not be worth it.



来源:https://stackoverflow.com/questions/13504637/yielding-with-an-idisposable-resource

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!