多线程EF代码可以使用优化
问题描述:
我有一个同步方法,它比较来自Web服务的项目列表,并同步数据库上的本地副本。多线程EF代码可以使用优化
此代码有效,运行良好,但我有强烈的感觉可以优化。我们正在处理200,000个项目,每个项目都有10-15个相关表格,所以这不是一个小小的工作量,但通常需要大约30-60分钟才能完成(如果有更多更新的项目比平时更多)。它确实适当地使用所有核心,在那里没有问题。
此代码删除已删除的项目。
var updatedListings = await _listingFeedService.GetListingsAsync();
Object lockContext = new Object();
var counter = 0; //Save changes every 300 listings
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = Environment.ProcessorCount - 1
};
//1.- Delete sold listings
var soldListings = _listingRepo.GetSoldListings(updatedListings);
Parallel.ForEach(soldListings, parallelOptions, (sl) =>
{
try
{
lock (lockContext)
{
_listingRepo.DeleteByMlsId(sl);
counter++;
if (counter > 100)
{
_listingRepo.Save();
counter = 0;
}
}
}
catch (Exception e)
{
syncReport.AppendLine($"{System.DateTime.Now} - ListingId: {sl} Status:Error | Error: { e.Message}");
}
});
_listingRepo.Save();
此代码插入新项目
//3.- Save the new listings
var newListings = _listingRepo.GetNewListings(updatedListings);
counter = 0;
Parallel.ForEach(newListings, parallelOptions, newListingMlsId =>
{
try
{
Listing listingToUpdate;
listingToUpdate = _listingFeedService.GetListingByMlsIdAsync(newListingMlsId).Result;
lock (lockContext)
{
_listingRepo.Add(listingToUpdate);
if (listingToUpdate.MlsId != 0)
{
counter++;
if (counter > 50)
{
_listingRepo.Save();
counter = 0;
}
}
}
}
catch (Exception e)
{
syncReport.AppendLine($"{System.DateTime.Now} - ListingId: {newListingMlsId} Status:Error | Error: { e.Message}");
}
});
_listingRepo.Save();
这将是更适合http://codereview.stackexchange.com/ –
对不起,将删除 – adam3039
好吧,因为它现在,它确实属于代码审查。另一方面,如果你有特定的问题并需要帮助,那么可以,在这里可以问这个问题,但是你需要明确你想要解决的具体问题。说得通? –