c# - 如何异步提交多条记录到数据库?

标签 c# performance azure scalability record

我在单击按钮时使用以下方法将记录添加到 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/

相关文章:

c# - Json.net getter 属性未序列化

java - 解析一行数据: split vs regex

java - 具有巨大字符串响应的 Tomcat 性能

c# - Azure api 请求被中止 : Could not create SSL/TLS secure channel. http 客户端在调用某些 Web api 时

c# - 我可以从 C# 类创建 VB 类的对象吗

c#计算数组之间的重叠

python - 在 python 中为什么如果排名 : is faster than if rank ! = 0:

azure - 从 ADF Webhook 事件调用 Azure 自动化 Runbook - 失败,显示 "Cannot bind argument to parameter ' InputObject',因为它为空。”

angular - 如何在 Mac 上使用 Visual Studio Code 将 Azure 发布设置文件导入到 Angular 项目?

c# - NHibernate:如何将查询与 anD 条件结合起来?