Using EF and Parallel.ForEach– is there a way to lock EF but allow more than just a single thread?

List<string> mergedList = new List<string>() myDbContext conn = new myDbContext(); Parallel.ForEach(fileList, file => { //ReadFile and get some lines //Create list of EF objects representing each row lock(mergedList) { mergedList.AddRange(selectedLines) } lock (conn) { conn.AddRange(listOfEFObjects) } }); 

Earlier I was just using a simple foreach and it was very slow. Parallel made it much faster but then I discovered the problem with sharing objects between multiple thread. After some reading, I started using lock and it worked fine in the beginning but at some point in the execution, the database would always time out and the program would crashout. So I moved my context instantiation outside the parallel and put a lock on it.

Now, I have a hangup at the context. The object list creation used to be what took the longest time, but now that happens quickly but dbcontext can't move fast enough. I read EF is not threadsafe but is it possible to maybe let 2-3 threads through the lock but not all the threads hammering away at the server?

Also, when I'm not using the dbcontext in a using block, do I have to manually Dispose() it?

by pope_says via /r/csharp

Leave a Reply