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 617805
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T18:28:32+00:00 2026-05-13T18:28:32+00:00

I have an example that I can get to break every time I use

  • 0

I have an example that I can get to break every time I use an iterator, but it works fine with a for loop. All code uses variables local to the executing method. I am stumped. There is either a fact about iterators that I am not aware of, or there is an honest to goodness bug in .Net. I’m betting on the former. Pleae help.

This code reliably work every time. It loops through (let’s say 10) all elements one at a time and starts a new thread, passing the integer to the new thread as an argument in a method. It starts 10 threads, one for each item.
1,2,3,4,5,6,7,8,9,10 – this always works.

WORKING CODE:

//lstDMSID is a populated List<int> with 10 elements.
for(int i=0; i<lstDMSID.Count; i++) 
{
    int dmsId = lstDMSID[i];
    ThreadStart ts = delegate
    {
        // Perform some isolated work with the integer
        DoThreadWork(dmsId);  
    };
    Thread thr = new Thread(ts);
    thr.Name = dmsId.ToString();
    thr.Start();
 }

And this code actually repeat elements. It iterates through (let’s say 10) all elements one at a time and starts a new thread. It starts 10 threads, but it does not reliably get all 10 integers. I am seeing it start 1,2,3,3,6,7,7,8,9,10. I am losing numbers.

BUSTED CODE:

//lstDMSID is a populated List<int> with 10 elements.
foreach(int dmsId in lstDMSID) 
{
    ThreadStart ts = delegate
    {
        // Perform some isolated work with the integer
         DoThreadWork(dmsId);
    };
    Thread thr = new Thread(ts);
    thr.Name = dmsId.ToString();
    thr.Start();
}
  • 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-13T18:28:33+00:00Added an answer on May 13, 2026 at 6:28 pm

    The problem is based on the closure generated for your scope…

    The same problem would happen in your for loop, were you to rewrite it like so (BAD CODE!):

    // ...Closure now happens at this scope...
    for(int i=0;i<lstDMSID.Count;i++) 
    {
        ThreadStart ts = delegate
        {
            DoThreadWork(lstDMSID[i]); // Eliminate the temporary, and it breaks!
        };
        Thread thr = new Thread(ts);
        thr.Name = dmsId.ToString();
        thr.Start();
    }
    

    The issue is, when you close over a variable in a delegate (in your case, dmsId), the closure happens at the scope where the variable is being declared. When you use a for or a foreach loop, the closure happens in the scope of the for/foreach statement, which is one level too high.

    Introducing a temporary variable inside the foreach loop will correct the issue:

    foreach(int dmsId in lstDMSID) 
    {
        int temp = dmsId; // Add temporary
        ThreadStart ts = delegate
        {
            DoThreadWork(temp); // close over temporary, and it's fixed
         };
         Thread thr = new Thread(ts);
         thr.Name = dmsId.ToString();
         thr.Start();
    }
    

    For a more detailed discussion of what is happening, I’d recommend reading Eric Lippert’s blog post: “Closing over the loop variable considered harmful”.

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

Sidebar

Related Questions

No related questions found

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.