我在单击按钮时使用以下方法将记录添加到 Azure 数据中。但我想知道在性能和可扩展性方面是否有更好的方法来将数据提交到数据库,而无需为每个数据创建新项目新纪录?
这就是我目前向 Azure 移动服务提交数据的方式:
Item itemOne = new Item { Repititions = " " + fingersSpreadScoreCntr.ToString(), Date = " " + DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"), User = "Ted Bundy" , Exercise = "Fingers Spread"};
await App.MobileService.GetTable<Item>().InsertAsync(itemOne);
Item itemTwo = new Item { Repititions = " " + fistHeldScoreCntr.ToString(), Date = " " + DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"), User = "Joe Bloggs", Exercise = "Fist Held" };
await App.MobileService.GetTable<Item>().InsertAsync(itemTwo);
Item itemThree = new Item { Repititions = " " + waveOutScoreCntr.ToString(), Date = " " + DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"), User = "George Bush", Exercise = "Wrist Extension" };
await App.MobileService.GetTable<Item>().InsertAsync(itemThree);
最佳答案
据我所知,移动服务表中没有批量插入功能。
可以加速多次插入的一件事是异步且并行地执行它们。在您的代码示例中,您正在等待 (await
) 每个 InsertAsync
完成,然后再开始下一个。调用所有插入然后等待它们全部完成会更快。示例代码可能如下所示:
var table = App.MobileService.GetTable<Item>();
Item itemOne = new Item { Repititions = " " + fingersSpreadScoreCntr.ToString(), Date = " " + DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"), User = "Ted Bundy", Exercise = "Fingers Spread" };
Item itemTwo = new Item { Repititions = " " + fistHeldScoreCntr.ToString(), Date = " " + DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"), User = "Joe Bloggs", Exercise = "Fist Held" };
Item itemThree = new Item { Repititions = " " + waveOutScoreCntr.ToString(), Date = " " + DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"), User = "George Bush", Exercise = "Wrist Extension" };
await Task.WhenAll(
table.InsertAsync(itemOne),
table.InsertAsync(itemTwo),
table.InsertAsync(itemThree));
这样您还可以消除每次插入后不必要的上下文切换。
Why should I prefer single 'await Task.WhenAll' over multiple awaits?
关于c# - 如何异步提交多条记录到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27256354/