C# 等待完成异步方法
我使用异步方法将数据插入数据库:C# 等待完成异步方法,c#,sqlite,async-await,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 rout
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);
});
}
});
}
但当我启动这段代码时,我在调试窗口中收到“创建表”和“插入记录”消息之前的“完成”消息
为什么以及如何修复它?您需要打开
异步任务
,而不是异步无效
和等待
您的方法:
public async Task InsertRoutes(ObservableCollection<RouteEO> routes)
以下是我的问题的答案:
[测试]
public void TestAsyncTableQueryToListAsync()
{
var conn=GetConnection();
conn.CreateTableAsync().Wait();
//创建。。。
Customer=this.CreateCustomer();
conn.InsertAsync(customer.Wait();
//查询。。。
var query=conn.Table();
var task=query.ToListAsync();
task.Wait();
var items=task.Result;
//检查。。。
varloaded=items.Where(v=>v.Id==customer.Id).First();
Assert.AreEqual(customer.Email,loaded.Email);
}
async void
仅支持异步UI事件处理程序。(将其视为“向后兼容性案例”)在该特定用例之外,切勿使用async void
(不仅因为它可以防止任务被正确等待,还可以防止系统知道任务执行过程中是否出错。)可能的重复
public async Task InsertRoutes(ObservableCollection<RouteEO> routes)
await sqlController.InsertInspections(DataController.InspectionList);
Debug.WriteLine("Done");
[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);
}