With this class:
class Block {
ObjectId Id { get; set; }
List<Item> ListOfItems;
}
I'm testing the following method, that just adds and Item to certain Block's ListOfItems field:
async Task AddItem(Block block, Item item) {
var updateDefinition = Builders<Block>.Update
.AddToSet(b => b.ListOfItems, item);
var result = await blocksCollection.UpdateOneAsync(
b => b.BlockId == block.BlockId, updateDefinition);
// however the synchronous version works:
// var result = blocksCollection.UpdateOneAsync(
// b => b.BlockId == block.BlockId, updateDefinition).Result;
if (result.ModifiedCount != 1)
throw new DbException();
}
This is the test:
async Task AddItemsTest() {
await Task.WhenAll(Enumerable.Range(0, 20).Select(
i => AddItem(certainBlock, new Item())));
}
Now if I run it asynchronously (with await on blocksCollection.UpdateOneAsync method), sometimes the result.ModifiedCount is 0 and not 1 (approx. 1 to 17 times), which throws the DbException.
When I run it synchronously (no await, with .Result), everything runs fine and all 20 items are added.
Why is that? what's wrong with the async version?
