You should probably check the SQL statements that you are executing, not the loop. The loop will process ALL rows returned by the statement in parallel. Exiting the loop will not stop the execution of the instruction; it will just stop processing the results.
LINQ executes a query when you try to list its results, not when you try to access one of them. In your example, this is the moment when you pass the request variable to Parallel.ForEach and convert to IEnumerable. Then Parallel.ForEach takes each row of results and tries to process it in parallel.
I suspect you have a large table that you are querying without any WHERE criteria. As a result, your connection timed out after the default execution timeout (about 60 seconds, I think). If you want to get a certain number of rows, you should use the e TOP command in SQL or the Take () method in LINQ, for example. calling
Parallel.ForEach(query.Take(10),
instead of just passing the request.
If you want to limit the rows returned by the SQL or LINQ statement, you must do this in the expression itself, and not try to limit the results after they are returned. Getting unnecessary row results will significantly slow down your database server and lead to possible deadlocks.
source share