等待完成异步方法

本文关键字:异步方法 等待 | 更新日期: 2023-09-27 18:24:43

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

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

但当我启动此代码时,在"创建表"answers"插入记录"消息之前,我会在"调试"窗口中收到"完成"消息。

为什么以及如何修复?

等待完成异步方法

您需要启用async Task而不是async voidawait您的方法:

public async Task InsertRoutes(ObservableCollection<RouteEO> routes)

然后:

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

以下是我的问题的答案: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);
    }