1

How can I make an asynchronous insert/update to MongoDB in C#? What is the terminology for lazy-persistence?

  • write-behind
shA.t
  • 16,580
  • 5
  • 54
  • 111
Serhat Dincel
  • 195
  • 1
  • 3
  • 12

2 Answers2

1

MongoDB inserts are by default kind of asynchronous since it's fire-and-forget. The error check is an explicit operation or you have to enable the safe mode on the driver level. If you need true asynchronous operations: use a message queue.

  • Not sure that *"inserts are by default kind of asynchronous"* was true as of the time this answer was written. According to this [official blog post](https://www.mongodb.com/blog/post/introducing-20-net-driver) from 2015, async operations were introduced only in the 2.0 driver version, which was followed by SO questions such as [this one](https://stackoverflow.com/questions/30091922/understanding-the-changes-in-mongodb-new-c-sharp-driver-async-and-await). – OfirD Oct 02 '19 at 09:25
0

In caching world 'lazy-persistence' would be called write-behind. Check this out: Cache/Wikipedia

Probably the easiest way is to use the C# async method calls. This will tell you how:

The code would look something like:

  • define your own delegate:

        private delegate void InsertDelegate(BsonDocument doc);
    
  • use it

        MongoCollection<BsonDocument> books = database.GetCollection<BsonDocument>("books");
        BsonDocument book = new BsonDocument {
            { "author", "Ernest Hemingway" },
            { "title", "For Whom the Bell Tolls" }
        };
    
        var insert = new InsertDelegate(books.Insert);
    
        // invoke the method asynchronously
        IAsyncResult result = insert.BeginInvoke(book, null, null);
    
        //  DO YOUR OWN WORK HERE
    
        // get the result of that asynchronous operation
        insert.EndInvoke(result);
    

Hope that helps.

grzeg
  • 338
  • 1
  • 6