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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T02:28:01+00:00 2026-06-06T02:28:01+00:00

I just encountered the following behavior: for (var i = 0; i < 50;

  • 0

I just encountered the following behavior:

for (var i = 0; i < 50; ++i) {
    Task.Factory.StartNew(() => {
        Debug.Print("Error: " + i.ToString());
    });
}

Will result in a series of “Error: x”, where most of the x are equal to 50.

Similarly:

var a = "Before";
var task = new Task(() => Debug.Print("Using value: " + a));
a = "After";
task.Start();

Will result in “Using value: After”.

This clearly means that the concatenation in the lambda expression does not occur immediately. How is it possible to use a copy of the outer variable in the lambda expression, at the time the expression is declared? The following will not work better (which is not necessarily incoherent, I admit):

var a = "Before";
var task = new Task(() => {
    var a2 = a;
    Debug.Print("Using value: " + a2);
});
a = "After";
task.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-06-06T02:28:07+00:00Added an answer on June 6, 2026 at 2:28 am

    This has more to do with lambdas than threading. A lambda captures the reference to a variable, not the variable’s value. This means that when you try to use i in your code, its value will be whatever was stored in i last.

    To avoid this, you should copy the variable’s value to a local variable when the lambda starts. The problem is, starting a task has overhead and the first copy may be executed only after the loop finishes. The following code will also fail

    for (var i = 0; i < 50; ++i) {
        Task.Factory.StartNew(() => {
            var i1=i;
            Debug.Print("Error: " + i1.ToString());
        });
    }
    

    As James Manning noted, you can add a variable local to the loop and copy the loop variable there. This way you are creating 50 different variables to hold the value of the loop variable, but at least you get the expected result. The problem is, you do get a lot of additional allocations.

    for (var i = 0; i < 50; ++i) {
        var i1=i;
        Task.Factory.StartNew(() => {
            Debug.Print("Error: " + i1.ToString());
        });
    }
    

    The best solution is to pass the loop parameter as a state parameter:

    for (var i = 0; i < 50; ++i) {
        Task.Factory.StartNew(o => {
            var i1=(int)o;
            Debug.Print("Error: " + i1.ToString());
        }, i);
    }
    

    Using a state parameter results in fewer allocations. Looking at the decompiled code:

    • the second snippet will create 50 closures and 50 delegates
    • the third snippet will create 50 boxed ints but only a single delegate
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am just starting working with jquery and have encountered the following problem <div
I just encountered a weird error which saying that find is not a member
Hi I have just started learning WCF and I have encountered an error I
I have just encountered this following code: public class TestFinally { public static void
I just encountered the following situation. I have an Android app with a scenario
I encountered a stored procedure that had the following error handling block immediately after
I just encountered the following code (slightly simplified): /* periodically requests garbagecollect to improve
I am writing a PHP application, and I've just encountered a really wierd error.
While running a perl program I encountered the following error *** glibc detected ***
Just learning C++, encountered an issue that i'm not really sure why the following

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.