开发者

Asynchronous insert to MongoDB in C#

开发者 https://www.devze.com 2023-02-23 23:21 出处:网络
How can I make an asynchronous insert/update to M开发者_C百科ongoDB in C#? What is the terminology for lazy-persistence?

How can I make an asynchronous insert/update to M开发者_C百科ongoDB in C#? What is the terminology for lazy-persistence?

  • write-behind


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号