等待完成异步方法

时间:2014-09-26 15:11:53

标签: c# sqlite async-await

我有将数据插入数据库的异步方法:

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

但是当我启动此代码时,我得到了#34;完成&#34;调试窗口中的消息&#34;表创建&#34;和&#34;记录插入&#34;消息。

为什么以及如何解决?

2 个答案:

答案 0 :(得分:1)

您需要转换async Task而不是async voidawait您的方法:

public async Task InsertRoutes(ObservableCollection<RouteEO> routes)

然后:

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

答案 1 :(得分: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);
    }