【问题标题】:How to submit multiple records to a database asynchronously?如何将多条记录异步提交到数据库?
【发布时间】:2015-01-31 02:36:53
【问题描述】:

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

【问题讨论】:

  • 什么是“*提交数据到数据库而不为每个新记录创建新项目*”,批量插入?

标签: c# performance azure scalability record


【解决方案1】:

据我所知,Mobile Service Table 中没有批量插入 功能。 可以加速多个插入的一件事是异步和并行执行它们。在您的代码示例中,您正在等待 (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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2016-02-06
    相关资源
    最近更新 更多