将大量记录插入Sqlite数据库

时间:2013-06-06 21:33:55

标签: c# sqlite windows-8 microsoft-metro async-await

在我的Windows 8 metro应用程序中,我有一个SQLite数据库中的表,有时必须使用大量记录(大约500到600)进行更新。我从Web服务获取记录,然后遍历记录并将它们插入表中。问题是此操作大约需要10到15秒,并且它正在锁定包括进度条的UI。代码如下。

await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
    foreach (var item in body3)
    {
        db.Insert(new Site
           {
              siteName = item.siteName,
              siteAddress = item.siteAddress,
              siteCity = item.siteCity,
              siteState = item.siteState,
              siteID = item.siteID
           });
        progressBar.Value = i;                                
        i++;
    }
});

我认为这是SQLite的一个问题。我似乎无法从中捕获异常。

我认为我真正的问题是如何让它在另一个线程中正确运行,因此它不会影响UI。我并不担心插入记录需要一段时间。我只是想让UI保持响应。

2 个答案:

答案 0 :(得分:3)

- 不要从循环中的每个插入更新UI ...如果需要,可能每20%

- 使用交易 - http://www.sqlite.org/faq.html#19 在这里Improve INSERT-per-second performance of SQLite?

答案 1 :(得分:0)

尝试这种方式。

foreach (var item in body3)
{
    db.RunInTransaction(() =>
    {
        db.Insert(new Site
        {
            siteName = item.siteName,
            siteAddress = item.siteAddress,
            siteCity = item.siteCity,
            siteState = item.siteState,
            siteID = item.siteID
        });
    });
    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        progressBar.Value = i;                                
        i++;
    });
}