c# - 我怎样才能更快地运行这个 Entity Framework 示例

标签 c# multithreading entity-framework parallel-processing async-await

我有这段代码可以将大约 1500 条记录添加到数据库中:

async void button7_Click(object sender, EventArgs e)
{
    var task = await Task.Run(() =>
    {
        Random rnd = new Random();
        for (int i = 0; i <= 1500; i++)
        {
            db.Tbls.Add(new Tbl()
            {
                Name = "User" + i + 1,
                Num = rnd.Next(10, i + 10) / 10
            });
            progress.Report(i * 100 / 1500);
        }

        db.SaveChanges();
        return db.Tbls.Count();

    });
}

但完成该过程大约需要 4 秒,但因为我使用了 async/await,它不会卡住 UI。现在我的问题是:如何改进此代码以使其运行得更快。我如何在这里使用并行编程?您能举例说明如何使用 TPL 吗?

编辑:

我按照建议使用了并行循环和 AddRange,但没有效果。在所有建议的方式中,我的过程仍然需要大约 4 秒。如果有人可以帮助我解决这个问题,我将不胜感激。

最佳答案

如果性能是目标,那么您应该使用 EF 以外的东西,例如 dapper (StackOverflow.com 使用的是同样的东西)或原始 ADO.Net .除此之外,您可以通过禁用 change auto detection 来提高 Entity Framework 的性能。和 validation on save :

yourDbContext.Configuration.AutoDetectChangesEnabled = false;
yourDbContext.Configuration.ValidateOnSaveEnabled = false;

您应该将上述代码与使用 AddRange 的@Evk 建议结合起来。

另一种可能有助于加快插入速度的解决方案是使用 BulkInsert (图片取自 here ):

enter image description here

关于c# - 我怎样才能更快地运行这个 Entity Framework 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37374480/

相关文章:

c# - 如何观察DbSet<T>的Add Action ?

c# - 如何在不丢失强类型的情况下返回代码优先 Entity Framework 中的 DbGeography.Distance 计算值?

c# - 使用列表框中对象的属性

c# - 使用 Web 表单将数据插入多个表

c# - .NET 依赖管理和标记/分支

Python Asyncio & Websocket 如何避免全局变量?

wpf - 在不同的 UI 线程中打印 DocumentViewer 的内容

python - 在运行线程中显示 chaco 图

c# Json.net DbGeography 反序列化错误

c# - 将 DbContext 与回发一起使用?