4

I am playing with Task functions and found a pretty strange problem that I run Task in for loop and pass the parameters to function (i) the loop count is 100. As I expected the output would be like this.
1
2
3
4
5
But the output I get from this function is
100
100
100
I mean it won't change to new parameters. For more details I uploaded the whole project.

Download Sample Program that I made!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        CheckForIllegalCrossThreadCalls = false;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Task.Factory.StartNew(() => button_tast());
    }
    void button_tast()
    {
        Task[] tk =new Task[100];
        for (int i = 0; i < 100; i++)
        {
            tk[i] = Task.Factory.StartNew(() => taskThread(i));
        }
        Task.WaitAll(tk);
    }
void taskThread(int i){
    listBox1.Items.Add(i);
}
}
}
4
  • 4
    Please post the relevant code here. May 20, 2013 at 14:33
  • 8
    Eric Lippert's Closing over Loop variables considered harmful May 20, 2013 at 14:35
  • @Damien_The_Unbeliever That article is with respect to foreach, it's not really about for, for which it's clear that the scope of the variable ought to be outside the loop.
    – Servy
    May 20, 2013 at 14:41
  • @Servy - it discusses what closing over a loop variable means, using foreach. It also, right at the top, tells you that the foreach behaviour changes for c# 5, but that for isn't changed. I thought it was a useful enough signpost. May 20, 2013 at 14:44

2 Answers 2

8

It's because you're closing over the loop variable. You can rewrite the loop as

for (int i = 0; i < 100; i++)
{
    int taskNumber = i
    tk[i] = Task.Factory.StartNew(() => taskThread(taskNumber));
}

and you'll be fine

2
  • 1
    If he hadn't access listBox1 in Tasks.
    – I4V
    May 20, 2013 at 14:38
  • Wow, Thanks man its working + I gain pretty nice knowledge thanks!
    – Capripio
    May 20, 2013 at 14:40
0

The problem is that from the point of view of the Tasks, the variable i is global, and can be modified in a non-threadsafe manner. This is easily rectified though....

        for (int i = 0; i < 100; i++)
        {
            int localCopy = i;
            tk[i] = Task.Factory.StartNew(() => taskThread(localCopy));
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.