Excerpt from C# Driver:
It is important that a cursor cleanly release any resources it holds. The key to guaranteeing this is to make sure the Dispose method of the enumerator is called. The foreach statement and the LINQ extension methods all guarantee that Dispose will be called. Only if you enumerate the cursor manually are you responsible for calling Dispose.
A cursor “res” created by calling:
var res = images.Find(query).SetFields(fb).SetLimit(1);
doesn’t have Dispose method. How do I dispose of it?
The query returns a
MongoCursor<BsonDocument>which doesn’t implementIDisposable, so you can’t use it in a using block.The important point is that the cursor’s enumerator must disposed, not the cursor itself, so if you were using the cursor’s
IEnumerator<BsonDocument>directly to iterate over the cursor then you’d need to dispose it, like this:However, you’d probably never do this and use a foreach loop instead. When an enumerator implements IDisposable, as this one does, looping using foreach guarantees its
Dispose()method will be called no matter how the loop terminates.Therefore, looping like this without any explicit disposing is safe:
As is evaluating the query with Enumerable.ToList<T>, which uses a foreach loop behind the scenes: