Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 870337
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T10:27:24+00:00 2026-05-15T10:27:24+00:00

I like the simplicity of the Parallel.For and Parallel.ForEach extension methods in the TPL.

  • 0

I like the simplicity of the Parallel.For and Parallel.ForEach extension methods in the TPL. I was wondering if there was a way to take advantage of something similar or even with the slightly more advanced Tasks.

Below is a typical usage for the SqlDataReader, and I was wondering if it was possible and if so how to replace the while loop below with something in the TPL. Because the reader can’t provide a fixed number of iterations the For extension method is not possible which leaves dealing with Tasks I would gather. I was hoping someone may have tackled this already and worked out some do’s and don”s with ADO.net.

using (SqlConnection conn = new SqlConnection("myConnString"))
using (SqlCommand comm = new SqlCommand("myQuery", conn))
{
    conn.Open();

    SqlDataReader reader = comm.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
            // Do something with Reader
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T10:27:25+00:00Added an answer on May 15, 2026 at 10:27 am

    You’re almost there. Wrap the code you posted in a function with this signature:

    IEnumerable<IDataRecord> MyQuery()
    

    and then replace your // Do something with Reader code with this:

    yield return reader;
    

    Now you have something that works in a single thread. Unfortunately, as you read through the query results it’s return a reference to the same object each time, and the object just mutates itself for each iteration. This means that if you try to run it in parallel you’ll get some really odd results as parallel reads mutate the object used in different threads. You need code to take a copy of the record to send to your parallel loop.

    At this point, though, what I like to do is skip the extra copy of the record and go straight to a strongly-typed class. More than that, I like to use a generic method to do it:

    IEnumerable<T> GetData<T>(Func<IDataRecord, T> factory, string sql, Action<SqlParameterCollection> addParameters)
    {
        using (var cn = new SqlConnection("My connection string"))
        using (var cmd = new SqlCommand(sql, cn))
        {
            addParameters(cmd.Parameters);
    
            cn.Open();
            using (var rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    yield return factory(rdr);
                }
            }
        }
    }
    

    Assuming your factory methods create a copy as expected, this code should be safe to use in a Parallel.ForEach loop. Calling the method would look something like this (assuming a an Employee class with a static factory method named “Create”):

    var UnderPaid = GetData<Employee>(Employee.Create, 
           "SELECT * FROM Employee WHERE AnnualSalary <= @MinSalary", 
           p => {
               p.Add("@MinSalary", SqlDbType.Int).Value = 50000;
           });
    Parallel.ForEach(UnderPaid, e => e.GiveRaise());
    

    Important Update:
    I’m not as confident in this code as I once was. A separate thread could still mutate the reader while another thread is in the process of making it’s copy. I could put a lock around that, but I’m also concerned that another thread could call update the reader after the original has itself called Read() but before it begins to make the copy. Therefore, the critical section here consists of the entire while loop… and at this point, you’re back to single-threaded again. I expect there is a way to modify this code to work as expected for multi-threaded scenarios, but it will need more study.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I particularly like the simplicity of using STL containers in the straightforward way. I
I very much like the simplicity of calling remote methods via Java's RMI, but
I have a database table that stores imported information. For simplicity, its something like:
I like the apparent simplicity of JdbcTemplate but am a little confused as to
I like HeidiSQL software very much for its simplicity, however I miss the phpMyAdmin
Like setFont(QFont(Helvetica,16,1)) ,I want to summerize these fonts.However,I dont't know how many fonts there
Like the title says, I'm wondering if the use of WebClient is the proper
Like in topic. It is possible to do it? Or make something to use
I'd like to have a logo (say it's square for simplicity) with 4 links
I like the simplicity of the Simple Repository , this looks ideal for simple

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.