2017-02-27 48 views
0

LogEntry继承的LogRecord定义:MongoDB的C#CreateOneAsync不返回

[BsonRepresentation(BsonType.ObjectId)] 
internal string   parent { get; set; } 

数据库和收集已经与数据中存在和我运行:只需

internal static async void CreateIndex() { 
    try { 
     var collection = db.GetCollection<LogEntry>(typeof(LogEntry).Name); 
     var name = await collection.Indexes.CreateOneAsync(
      Builders<LogEntry>.IndexKeys.Ascending(entry => entry.parent)); 
     Console.WriteLine("index name is {0}", name); 
    } catch (Exception exc) { 
     Console.WriteLine("oh no"); 
    } 
} 

随着双方WriteLines断点,程序在调用CreateOneAsync并且Compass在该集合的数据库中不显示索引时终止。

那么如何确定为什么CreateOneAsync失败?

解决方案(谢谢@Veeram):需要使用.Result对CreateOneAsync的调用,并在我的CreateIndex方法上放下async/await。

+0

的[我为什么不能在异步方法调试代码?(可能的复制http://stackoverflow.com/questions/36733237/why-cant-i-debug-code-in-an-异步方法) – Veeram

+0

@Veeram我不明白,实际上。我实际上并不希望我的CreateIndex是异步的。我必须在其上放置async关键字才能使用CreateOneAsync等待。我在你引用的文章中看到,最终会使用Wait()。 (我试图通过死记硬背,并没有编译(不能解决符号等待)。)但无论如何,我想尽快结束异步链。我错过了什么? – koan911

回答

0

将您的方法更新为基本同步版本。

请注意使用Result完成调用线程中的调用。

internal static void CreateIndex() { 
    try { 
     var collection = db.GetCollection<LogEntry>(typeof(LogEntry).Name); 
     var name = collection.Indexes.CreateOneAsync(
      Builders<LogEntry>.IndexKeys.Ascending(entry => entry.parent)).Result(); 
     Console.WriteLine("index name is {0}", name); 
    } catch (Exception exc) { 
     Console.WriteLine("oh no"); 
    } 
} 
+0

是的,我认为这是它,谢谢。它无论如何编译,并没有返回,但也没有终止。如果我得到一个索引,我会标记你的答案。 – koan911