2014-09-26 188 views
-3

我有一個將數據插入到數據庫異步方法:等待完成異步方法

public async void InsertRoutes(ObservableCollection<RouteEO> routes) 
{ 
    connection.CreateTableAsync<RouteEO>().ContinueWith((result) => 
    { 
    Debug.WriteLine("Routes table created"); 
    foreach (var route in routes) 
    { 
     var query = connection.Table<RouteEO>(). 
         Where(v => v.InspectionId == route.InspectionId && v.EO_id == route.EO_id); 

     query.ToListAsync().ContinueWith((t) => 
     { 
      Debug.WriteLine("Route record inserted or updated"); 
      if (t.Result.Any()) 
       connection.UpdateAsync(route); 
      else 
       connection.InsertAsync(route); 
     }); 
    } 
    }); 
} 

我想打電話給它,並執行代碼的下一行,只有當方法執行將完成:

sqlController.InsertInspections(DataController.InspectionList); 
Debug.WriteLine("Done"); 

但是,當我啓動此代碼時,在「表創建」和「記錄插入」消息之前,在調試窗口中收到「完成」消息。

爲什麼以及如何解決?

+1

'異步void *僅支持*以支持異步UI事件ha ndlers。 (考慮它是一個「向後兼容的情況)。除了特定的用例外,***從不***使用'async void'(不僅因爲它阻止了任務正確等待,而且還阻止了系統知道是否任務執行期間出錯) – David 2014-09-26 15:19:18

+0

[異步,等待和奇怪的結果]的可能重複(http://stackoverflow.com/questions/26062412/async-await-and-strange-result) – 2014-09-26 15:23:58

回答

0

這是回答我的問題:https://github.com/praeclarum/sqlite-net/blob/master/tests/AsyncTests.cs

[Test] 
    public void TestAsyncTableQueryToListAsync() 
    { 
     var conn = GetConnection(); 
     conn.CreateTableAsync<Customer>().Wait(); 

     // create... 
     Customer customer = this.CreateCustomer(); 
     conn.InsertAsync (customer).Wait(); 

     // query... 
     var query = conn.Table<Customer>(); 
     var task = query.ToListAsync(); 
     task.Wait(); 
     var items = task.Result; 

     // check... 
     var loaded = items.Where (v => v.Id == customer.Id).First(); 
     Assert.AreEqual (customer.Email, loaded.Email); 
    } 
1

您需要打開async Task而不是async voidawait你的方法:

public async Task InsertRoutes(ObservableCollection<RouteEO> routes) 

然後:

await sqlController.InsertInspections(DataController.InspectionList); 
Debug.WriteLine("Done");