如何将多条记录异步提交到数据库
本文关键字:异步 提交 数据库 记录 | 更新日期: 2023-09-27 18:32:47
我正在使用以下方法单击按钮将记录添加到 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));
这样,您还可以消除每次插入后不必要的上下文切换。
为什么我应该更喜欢单个"await Task.WhenAll"而不是多个 await ?