Reputation: 1592
I am not very familiar with async in C#, but I am trying to understand it better. I am trying to process a list of documents in Mongo, and I am not sure if I have a race condition or if async is special causing this to be fine. Here is my example.
var docs = new Dictionary<string, BsonDocument>();
var result = db.GetCollection<BsonDocument>("mycollection").Find(new BsonDocument());
result.ForEachAsync((bsonDoc) =>
{
string name = bsonDoc.GetValue("name").AsString;
if (!docs.ContainsKey(name))
{
docs[name] = bsonDoc;
}
});
It seems like if two documents had the same name, then that if statement could be executed twice for the same name.
I am not sure why there doesn't seem to be a straight forward was to do a synchronous for each with the new mongo driver.
Can someone tell me how I should structure the above code, or why it isn't a race condition if I am wrong?
Thank you.
Upvotes: 1
Views: 5344
Reputation: 4135
According to this:
http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/crud/reading/
Finding all the documents in a collection is done with an empty filter and the method Find. Once we have a cursor (of type IAsyncCursor), we can iterate it like we manually iterate an IEnumerable.
So Find()
is returning an async cursor, which only ever points to one document at a time. The documentation doesn't say explicitly that ForEachAsync()
won't move the cursor position till after your lambda finishes, but that's presumably how it works (otherwise, the point of a cursor is defeated since you're loading up more than one record at a time into memory).
Thus, you should be safe doing what you are, and shouldn't encounter a race condition.
Upvotes: 2