Find和FindAsync的区别

30 浏览
0 Comments

Find和FindAsync的区别

我正在编写一个非常简单的查询,根据唯一的Id从集合中获取一个文档。在一些挫折后(我对mongo和异步/等待编程模型还不熟悉),我找到了解决方法:

IMongoCollection collection = // ...
FindOptions options = new FindOptions { Limit = 1 };
IAsyncCursor task = await collection.FindAsync(x => x.Id.Equals(id), options);
List list = await task.ToListAsync();
TModel result = list.FirstOrDefault();
return result;

它起作用了,很棒!但我一直看到有关"Find"方法的引用,于是我弄清楚了这个方法:

IMongoCollection collection = // ...
IFindFluent findFluent = collection.Find(x => x.Id == id);
findFluent = findFluent.Limit(1);
TModel result = await findFluent.FirstOrDefaultAsync();
return result;

结果证明,这个也起作用了,很棒!

我相信有一些重要的原因我们有两种不同的方法来实现这些结果。这些方法的区别是什么,我应该选择哪一个呢?

0