0

I'm trying to create tasks in a loop and each task uses different values as method parameter. However, I found all tasks are having the same parameter

            for(int i = 0; i < threads; i++)
        {
            tasks.Add(new Task( () => DownloadFunc(i) ));
        }

        WATCH.Reset();
        WATCH.Start();
        Parallel.ForEach(tasks, t => t.Start());
Svenmarim
  • 3,633
  • 5
  • 24
  • 56
LN.EXE
  • 59
  • 8
  • try storing the value of `i` in another variable and use that variable as the function parameter – windrunn3r.1990 May 19 '17 at 19:51
  • @JonSkeet The behavior of a capture `for` loop variable has never changed in C#'s history. – Servy May 19 '17 at 20:03
  • @Servy: Doh, you're right, it was foreach, of course. Deleted the comment :) – Jon Skeet May 19 '17 at 20:04
  • There must be lots of duplicates for this question... – Jon Skeet May 19 '17 at 20:04
  • @JonSkeet Found one that you answered ;) – Servy May 19 '17 at 20:05
  • On an unrelated note, there's no reason to *start* a bunch of tasks in parallel. Starting a task is *very* fast. It's slower to try to parallelize the loop than to just start the tasks in sequence. Additionally, you shouldn't really ever create unstarted tasks in the first place. Just use `Task.Run` to execute a function in a thread pool thread, rather than dealing with having unstarted tasks and starting them later. It's just creating something that can go wrong or cause confusion without really adding value. – Servy May 19 '17 at 20:07
  • @windrunn3r.1990 Thanks! This solved my problem. – LN.EXE May 22 '17 at 20:42
  • @Servy Yes, I understand that. This application is just for some tests and I'm trying to simulate the cases. – LN.EXE May 22 '17 at 20:43
  • @LiuGarry I don't see how that's a reason to do any of the things I mentioned in my comment. They're only going to cause problems and be more work, whether it's a small test or a production application. – Servy May 22 '17 at 20:44

0 Answers0