Starting a thread from a loop and identifying a Loop ID

I just started playing with streams today, and I came across something that I do not understand.

public void Main()
{ 
    int maxValue = 5;
    for (int ID = 0; ID < maxValue; ID++)
    {
        temp(ID);
    }
}

public void temp(int i)
{
    MessageBox.Show(i.ToString());
}

As a base one that works fine, but when I try to create a new thread for each, it only passes maxValue. Please do not pay attention to how bad it is to do, I wrote it just as a simplified example.

public void Main()
{ 
    int maxValue = 5;
    for (int ID = 0; ID < maxValue; ID++)
    {
        threads.Add(new Thread(() => temp(myString, rowID)));
        threads[rowID].Start();
    }
}

public void temp(string myString, int i)
{
    string _myString = myString;

    MessageBox.Show(i.ToString());
}

Given this, I have two questions: 1) Why is the method not called in a new thread that passes the identifier? 2) How to code it correctly?

+1
source share
1 answer

, ID, . , , , , ID maxValue. , :

for (int ID = 0; ID < maxValue; ID++)
{
    int copy = ID;
    threads.Add(new Thread(() => temp(myString, copy)));
    threads[rowID].Start();
}

. , # Java . foreach, , , , :

foreach (string url in urls)
{
    // Aargh, bug! Don't do this!
    new Thread(() => Fetch(url)).Start();
}

, . , , :

foreach (string url in urls)
{
    string urlCopy = url;
    new Thread(() => Fetch(urlCopy)).Start();
}
+9

All Articles