4

Anyone can help? When i write this code and run. The program show me error stated "There is already an open DataReader associated with this Command which must be closed first".

This is my code.

Parallel.For(0, MthRange, i => {
    PSUpfrontFeeForMonth[i] = CommissionSummary
        .Where(s => s.TransDate == oReportCommonFilter.fromDate.AddMonths(i))
        .Sum(s => s.PSUpfrontFee);

    if (!PSUpfrontFeeForMonth[i].HasValue)
    {
        PSUpfrontFeeForMonth[i] = 0;
    }
});

Thanks.

Regards, Jane

2
  • 3
    For the sake of readability you should mark any piece of code as 'Code Sample' and you can do this by highlighting the piece of code and clicking 101010 button. Commented Nov 26, 2010 at 7:16
  • Dude make an eager evaluation by Appending ToList() to your Linq Query and then do your in memory processing Parallel Commented Nov 26, 2010 at 8:10

3 Answers 3

4

Parallelizing database query is completely wrong for the following reasons:

  1. Query is issued against sql from each processor so multiple data readers will be opened -> 'error'
  2. No performance gain is achieved, in fact the program becomes slower because each processor is trying to connect to the database and no parallel processing is actually done since all query processing is done in sql! so the normal serial query is faster in this case.
Sign up to request clarification or add additional context in comments.

Comments

1

If you really need to have multiple database connections open simultaneously (as others have stated not necessarily a good idea) then you can usually specify in the connection string that this is needed.

Typical scenario in which I've used this is for using a DataReader to stream rows from a database table (as I don't know how many rows I need in advanced) and where I then need to make additional queries on other database tables. I do this rather than a single query as it would require multiple complex joins and my app has a good caching layer to reduce queries to the database.

For Microsoft SQL Server you add MultipleActiveResultSets=True; to the connection string

Comments

0

My guess would be something to do with how PSUpfrontFeeForMonth works internally is using data readers.

Since I have no idea how that works, first thing I would try would be to initialise the PSUpfrontFeeForMonth within the loop. Maybe that will ensure a dedicated data reader for each iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.