在使用块内,需要处理和重新启动 [英] Inside of using block, need to dispose and reinstantiate
问题描述
我正在尝试使用EF来提升将数千行写入数据库的性能。我发现SaveChanges()的速度在一个上下文中随着时间的推移而降低,并且在n个插入之后处理和重新创建上下文可以帮助这个。
I am trying to enhance the performance of writing thousands of rows to a db using EF. I have found that the speed of SaveChanges() degrades over time within a single context, and disposing and recreating the context after n inserts can help this.
using(Context context = new Context())
{
for(int i = 0; i < numberOfLines; i++)
{
context.Collection.AddObject(line);
if (i % 100 == 0)
{
context.SaveChanges()
// Here I would like to call dispose on context and then create a new one
}
}
}
当然,我需要使用或者做类似的事情,因为还有更多的事情,我需要确保在任何时间抛出异常时调用处理。
Of course, I need to use using or do something similar because there is a lot more going on and I need to ensure that dispose will be called if an exception gets thrown at any time.
任何想法?我知道我可以在一个try块之外声明这个上下文,然后最后用context.Dispose()方法。我显然不想这样做。
Any ideas? I know I can declare the context outside of a try block, and then have a finally with context.Dispose(). I obviously don't want to do that though.
编辑:我意识到我发布的代码段并不完全显示为什么我试图这样做。 for循环在IF语句外的其他位置调用context.SaveChanges()。所以当IF评估为真时,我已经多次调用SaveChanges()。
I realized the code snippet I posted doesn't totally show why I am trying to do this. The for loop calls context.SaveChanges() in other spots outside of the IF statement. So when the IF evaluates to true, I've called SaveChanges() a number of times already.
推荐答案
这听起来像你基本上是想批量处理一个集合。这很简单,使用 MoreLINQ (也在NuGet ):
It sounds like you basically want to process a collection in batches. That's simple using MoreLINQ (also on NuGet):
foreach (var batch in dataToUpload.Batch(100))
{
using (var context = new Context())
{
foreach (var item in batch)
{
...
}
context.SaveChanges();
}
}
除了其他的东西, / em>你想要实现的目标(IMO)比使用一个循环支持 i%100
更清楚。
Aside from anything else, that describes what you're trying to achieve (IMO) much more clearly than using one loop with a check for i % 100
in it.
( http://morelinq.googlecode.com 的原始链接不再有效,替换为当前的GitHub链接)
(Original link to http://morelinq.googlecode.com is no longer valid, replaced with current GitHub link)
这篇关于在使用块内,需要处理和重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!