I'm paging through a set of data (example of query below) to verify some information. When I use Parallel.ForEach, the SQL command to get the second page of results comes back empty. If I break on the return statement and move the active line back to the Repository, it will return the results I'm looking for. Changing the Parallel.ForEach to a standard C# foreach works as expected.
Example of the query:
SELECT TOP 500
StudentID,
StudentName
FROM Student
WHERE StudentVerified IS NULL
Example of the code...
while(true)
{
using(var rep = new Repository())
{
var students = rep.GetStudents();
if (students.Length == 0) return false;
Parallel.ForEach(students, (student) =>
{
rep.StudentVerified(student.StudentID, true);
});
}
}
Any help to figure out why the second page of results is coming back empty is appreciated. Thanks.
Repository.StudentVerifiedis not thread safe. You need to show the code for it.MaxDegreeOfParallelismto1in options (just for the sake of it) will likely result in it working too. Thus the problem isn't so much "Parallel.ForEach causing SQL query to not work" rather that your code is potentially not thread-safe. IfRepository.StudentVerifiedare all sharing the same db connection, that is perhaps your problem right there. Same applies to EF