0

I have a question on this program. It does not produce the correct result. I assume that it should give me output like + 1 + 2 - 1 + 3 - 2 + 4 - 3 + 5 - 4 - 5 (not order specific). However, it outputs + 1 + 2 - 2 + 3 - 3 + 4 - 4 + 5 - 5 - 5.

If I make a copy

MyStructure msCopy = ms;
Thread t = new Thread(() => { updateMe(msCopy); });

It outputs the correct value. I am using .net 3.5. What is the reason?

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        p.createThread();
    }

    List<MyStructure> structure = new List<MyStructure>();

    public void createThread()
    {
        foreach (MyStructure ms in structure)
        {
            System.Diagnostics.Debug.WriteLine("+ " + ms.ID);
            //MyStructure msCopy = ms;
            //Thread t = new Thread(() => { updateMe(msCopy); });
            Thread t = new Thread(() => { updateMe(ms); });
            t.Start();
        }

    }

    private void updateMe(MyStructure ms)
    {
        System.Diagnostics.Debug.WriteLine("- " + ms.ID);
    }

    public Program()
    {
        structure.Add(new MyStructure { ID = 1, Name = "A" });
        structure.Add(new MyStructure { ID = 2, Name = "B" });
        structure.Add(new MyStructure { ID = 3, Name = "C" });
        structure.Add(new MyStructure { ID = 4, Name = "D" });
        structure.Add(new MyStructure { ID = 5, Name = "E" });
    }
}

internal class MyStructure
{
    public int ID { get; set; }
    public String Name { get; set; }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Helic
  • 907
  • 1
  • 10
  • 25
  • something to do with closures although i never understood it. Copying it is the right thing to do – Weyland Yutani Oct 24 '13 at 15:05
  • Please read http://stackoverflow.com/questions/14907987/access-to-foreach-variable-in-closure – macpak Oct 24 '13 at 15:07
  • 1
    I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Oct 24 '13 at 15:09
  • Additional note: This behavior was changed in 4.0 to work as expected, but the links provided by others will explain a way that is forward-compatible. – Magus Oct 24 '13 at 15:11
  • 1
    @AlexBeisley It was changed in 5.0, not 4.0 – Servy Oct 24 '13 at 15:15
  • Thanks all for the comments. – Helic Oct 24 '13 at 15:15
  • @Servy, I meant .Net, but yes, C# 5 – Magus Oct 24 '13 at 15:22
  • 1
    @AlexBeisley The version of .NET is irrelevant; it is the C# language version that matters. Additionally, it was .NET 4.5 that came out with C# 5.0, although as I said it is the version of the language used that determines this functionality. – Servy Oct 24 '13 at 15:23

0 Answers0