开发者

c# Parallel loop error

开发者 https://www.devze.com 2023-01-27 14:11 出处:网络
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\".

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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号