Jane
Jane

Reputation: 51

c# Parallel loop error

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

Upvotes: 4

Views: 1415

Answers (3)

Ali Tarhini
Ali Tarhini

Reputation: 5358

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.

Upvotes: 4

RobV
RobV

Reputation: 28646

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

Upvotes: 1

Robert MacLean
Robert MacLean

Reputation: 39261

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.

Upvotes: 0

Related Questions