2017-02-27 52 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