0
我有一個同步方法,它比較來自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
好吧,因爲它現在,它確實屬於代碼審查。另一方面,如果你有特定的問題並需要幫助,那麼可以,在這裏可以問這個問題,但是你需要明確你想要解決的具體問題。說得通? –