async
の基本を理解しておくと役に立ちます / await
ややリークの多い抽象化であり、多くの落とし穴があるためです。
基本的に、2つのオプションがあります:
-
同期を維持します。この場合、
のようなもの.Result
を使用しても安全です。 および.Wait()
非同期呼び出しで、それぞれ、例えば// Insert: collection.InsertOneAsync(user).Wait(); // FindAll: var first = collection.Find(p => true).ToListAsync().Result.FirstOrDefault();
-
コードベースで非同期にします。残念ながら、それを非同期にすることは非常に「感染性」であるため、ほとんどすべてを非同期に変換するかどうかのどちらかです。注意してください、同期と非同期を誤って混合すると、デッドロックが発生します 。非同期を使用すると、MongoDBがまだ機能している間もコードを実行し続けることができるため、多くの利点があります。例:
// FindAll: var task = collection.Find(p => true).ToListAsync(); // ...do something else that takes time, be it CPU or I/O bound // in parallel to the running request. If there's nothing else to // do, you just freed up a thread that can be used to serve another // customer... // once you need the results from mongo: var list = await task;