Brian
Brian

Reputation: 38025

Parallel.ForEach causing SQL query to not work

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.

Upvotes: 0

Views: 632

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

From you comments you appear to be sharing a SqlConnection between requests. That class is not thread safe. SqlConnection is optimised to have many short lived connections, create the connection as you need it then dispose of it when you are done by using a using block.

Upvotes: 2

Related Questions