0

我有一个关于这个程序的问题。它不会产生正确的结果。我认为它应该给我像 + 1 + 2 - 1 + 3 - 2 + 4 - 3 + 5 - 4 - 5 的输出(不是特定于订单的)。但是,它输出 + 1 + 2 - 2 + 3 - 3 + 4 - 4 + 5 - 5 - 5。

如果我复制

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

它输出正确的值。我正在使用.net 3.5。是什么原因?

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; }
}
4

0 回答 0