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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T04:30:18+00:00 2026-05-19T04:30:18+00:00

I am making a first attempt at playing with the new Tasks, but something

  • 0

I am making a first attempt at playing with the new Tasks, but something is happening that I don’t understand.

First, the code, which is pretty straight-forward. I pass in a list of paths to some image files, and attempt to add a task to process each of them:

public Boolean AddPictures(IList<string> paths)
{
    Boolean result = (paths.Count > 0);
    List<Task> tasks = new List<Task>(paths.Count);

    foreach (string path in paths)
    {
        var task = Task.Factory.StartNew(() =>
            {
                Boolean taskResult = ProcessPicture(path);
                return taskResult;
            });
        task.ContinueWith(t => result &= t.Result);
        tasks.Add(task);
    }

    Task.WaitAll(tasks.ToArray());

    return result;
}

I’ve found that if I just let this run with, say, a list of 3 paths in a unit test, all three tasks use the last path in the provided list. If I step through (and slow down the processing of the loop), each path from the loop is used.

Can somebody please explain what is happening, and why? Possible workarounds?

  • 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-19T04:30:19+00:00Added an answer on May 19, 2026 at 4:30 am

    You’re closing over the loop variable. Don’t do that. Take a copy instead:

    foreach (string path in paths)
    {
        string pathCopy = path;
        var task = Task.Factory.StartNew(() =>
            {
                Boolean taskResult = ProcessPicture(pathCopy);
                return taskResult;
            });
        // See note at end of post
        task.ContinueWith(t => result &= t.Result);
        tasks.Add(task);
    }
    

    Your current code is capturing path – not the value of it when you create the task, but the variable itself. That variable changes value each time you go through the loop – so it can easily change by the time your delegate is called.

    By taking a copy of the variable, you’re introducing a new variable each time you go through the loop – when you capture that variable, it won’t be changed in the next iteration of the loop.

    Eric Lippert has a pair of blog posts which go into this in a lot more detail: part 1; part 2.

    Don’t feel bad – this catches almost everyone out 🙁


    Note about this line:

    task.ContinueWith(t => result &= t.Result);
    

    As pointed out in comments, this isn’t thread-safe. Multiple threads could execute it at the same time, potentially stamping on each other’s results. I haven’t added locking or anything similar as it would distract from the main issue that the question is interested, namely variable capture. However, it’s worth being aware of.

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

Sidebar

Related Questions

Im trying to make a funciton which allows me to add a new value
I'm making my first iOS App, and I'm facing my first (little) issue. The
I'm making some first steps in Typo3 and am currently trying to make a
I am making minor edits to a QTMovie in an application using NSDocument architecture
I am learning django-cms. I tried to make custom plugin which was quite successful
i know this sounds simple for some people out there. i also tried this
I'm trying to add a file upload script in php to a website I'm
In the app I'm working on, I have to make an HTTPS connection to
This question is related to: CS5 FLASH + AS3 Hello, I am simply trying
I have a list of numbers and I need to split into to corresponding

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.