我编写了一个函数,可以让我一次对特定数量的实体运行函数,并动态调整查询时间。然而,随着它继续处理实体,即使只处理一个实体,每个查询所需的时间也会逐渐增加。
public async Task Work(Expression<Func<dbase, bool>> predicate, Action<CollectionsMax, dbase> action)
{
try
{
using (var cmax = _cmax)
{
cmax.Configuration.AutoDetectChangesEnabled = false;
double count = await cmax.dbases.CountAsync(predicate);
var takeAmount = 1;
var taken = 0;
var takeTimer = new Stopwatch();
while (taken != (int) count)
{
cmax.Configuration.AutoDetectChangesEnabled = false;
takeTimer.Reset();
takeTimer.Start();
IQueryable<dbase> query = cmax.dbases.Where(predicate)
.OrderBy(o => o.id)
.Skip(taken)
.Take(Math.Min(takeAmount, (int) count - taken));
var take = await query.ToListAsync();
takeTimer.Stop();
Console.WriteLine("Took {0} and that took {1}ms", take.Count, takeTimer.ElapsedMilliseconds);
taken += take.Count;
if (takeTimer.ElapsedMilliseconds < 2000)
{
takeAmount = takeAmount + 5;
}
if (takeTimer.ElapsedMilliseconds > 2000)
{
takeAmount = takeAmount - 5;
}
if (takeAmount < 1)
takeAmount = 1;
Parallel.ForEach(take, obj => action(_max, obj));
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
输出:http://puu.sh/hxMSD/68dbf4f079.png