在c#中异步插入MongoDB

本文关键字:插入 MongoDB 异步 | 更新日期: 2023-09-27 17:49:45

如何在c#中对MongoDB进行异步插入/更新?惰性持久化的术语是什么?

    write - behind

在c#中异步插入MongoDB

MongoDB插入默认是异步的,因为它是即发即忘的。错误检查是一个显式操作,否则您必须在驱动程序级别启用安全模式。如果你需要真正的异步操作:使用消息队列

在缓存的世界里,'lazy-persistence'被称为write-behind。看看这个:Cache/Wikipedia

也许最简单的方法是使用c#的async方法调用。这将告诉您如何:

代码看起来像这样:

  • 定义你自己的委托:

        private delegate void InsertDelegate(BsonDocument doc);
    
  • 使用它
        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);
    

希望对你有帮助。