I'm looping through many different objects in entity framework, grabbing some related data and saving that data. I'm opening a new thread for each item since it takes a while to do the work in the method. However, I'm getting out of memory exceptions a couple thousand items into the loop. I'm trying to figure out where this problem is occurring and how to keep the multi-thread functionality, but fix the error. Any help is greatly appreciated. Thank you.
foreach (var prod in products)
{
try
{
new Thread(() =>
{
ParsePage(prod);
}).Start();
counter++;
Console.WriteLine(counter);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
public void ParsePage(Product p)
{
//New Repository
IDataRepository repo = new DataRepository();
//Grab related page report
PageReport pr = repo.PageReports.Where(c => c.ThePageType == "Product").FirstOrDefault(c => c.ThePageTypeID == p.ProductID);
//Do some stuff
//Save
repo.SavePageReport(pr);
}
DataRepositoryIDisposable? If so, try wrapping it in ausingstatement.DbContext? If so, maybe it should be disposable.AsNoTracking()in your grabbing query..