Assignment by IDisposable

Is there a way to get income through a one-time resource? The returned objects are IDisposable, but the element that it executes executes.

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, invoking this will not dispose of the using resource. I know that I can just use ToList and return it right away, but is there a way to handle this “correctly”, or do I need to save the tab on the IDisposable resource and get rid of it manually when done?

+8
c # yield-return
source share
1 answer

In short, you don’t have to worry about this while the caller of the method correctly processes IEnumerator objects.

IEnumerator implements IDisposable , and the logic used to create iterator blocks is actually smart enough to execute all incomplete finally blocks when they are located. The final block is created by calling using , and that is where the IDisposable resource is located.

Until the IEnumerator objects created from this IEnumerable are either completely iterated (in this case, the final call to MoveNext will reach the end of the using block and delete the resource) or the IDisposable client will be deleted.

Please note: if you are concerned that the user of your code may not correctly treat IEnumerator objects, then it is best not to use an iterator block with lazy evaluation. If you want to make sure that even if the caller is not “playing well,” then look forward to the method (i.e., take the code that you have, put the results in the list, and return this list). If the consequences of not disposing of the resource are primarily or completely related to performance (without freeing up some memory for a while longer, keeping an open connection, etc.), then this may not be a problem, but if you hold the lock permanently, the main problem (i.e. i.e. a blocked resource that can lead to deadlocks if not released), then the advantage of a lazy rating might not be worth it.

+7
source share

All Articles