MongoDB:处理游标

And*_*rey 7 c# mongodb mongodb-.net-driver

摘自C#驱动程序:

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.

通过调用创建的游标"res":

var res = images.Find(query).SetFields(fb).SetLimit(1);
Run Code Online (Sandbox Code Playgroud)

没有Dispose方法.我该如何处理它?

Chr*_*tow 9

查询返回一个MongoCursor<BsonDocument>未实现的查询IDisposable,因此您无法在using块中使用它.

重要的一点是光标的枚举器必须处理,而不是光标本身,所以如果你IEnumerator<BsonDocument>直接使用光标迭代光标,那么你需要处理它,如下所示:

using (var iterator = images.Find(query).SetLimit(1).GetEnumerator())
{
    while (iterator.MoveNext())
    {
        var bsonDoc = iterator.Current;
        // do something with bsonDoc
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,您可能永远不会这样做并使用foreach循环代替.当枚举器实现IDisposable时,就像这样,使用foreach循环保证Dispose()无论循环如何终止,都将调用其方法.

因此,在没有任何明确处理的情况下循环这样是安全的:

foreach (var bsonDocs in images.Find(query).SetLimit(1))
{
    // do something with bsonDoc                
}
Run Code Online (Sandbox Code Playgroud)

正如使用Enumerable.ToList <T>评估查询一样,它使用幕后的foreach循环:

var list = images.Find(query).SetLimit(1).ToList();
Run Code Online (Sandbox Code Playgroud)