我对这个程序有疑问。它不会产生正确的结果。我认为它应该给我输出像+ 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; }
}