【问题标题】:Asynchronous insert to MongoDB in C#在 C# 中异步插入到 MongoDB
【发布时间】:2015-08-26 13:12:34
【问题描述】:

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

  • 后写

【问题讨论】:

    标签: c# mongodb insert async-await


    【解决方案1】:

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

    【讨论】:

    • 不确定 "inserts are by default kind of asynchronous" 在编写此答案时是否正确。根据这个official blog post从2015年开始,异步操作仅在2.0驱动版本中引入,随后出现this one等SO问题。
    【解决方案2】:

    在缓存世界中,“惰性持久性”将被称为后写。看看这个:Cache/Wikipedia

    可能最简单的方法是使用 C# 异步方法调用。这将告诉你如何:

    代码如下所示:

    • 定义你自己的委托:

          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);
      

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 2020-05-22
      • 2021-08-12
      相关资源
      最近更新 更多