代码 1using System; 2using System.Collections; 3using System.Collections.Generic; 4using System.ComponentModel; 5using System.Data; 6using System.Drawing; 7using System.Text; 8using System.Windows.Forms; 9 10using System.Threading; 11 12namespace CSharpGeriac 13{ 14 public partial class Form1 : Form 15 { 16 public Form1() 17 { 18 InitializeComponent(); 19 20 Thread t = new Thread(new ThreadStart(ChangeLabel)); 21 t.Start(); 22 } 23 24 private void ChangeLabel() 25 { 26 myClassCollection coll = new myClassCollection(); 27 foreach (MyClass c in coll) 28 { 29 SetLabelText(c); 30 Thread.Sleep(1000); 31 } 32 } 33 34 private void SetLabelText(MyClass myClass) 35 { 36 // label.Text = number.ToString(); 37 // Do NOT do this, as we are on a different thread. 38 39 // Check if we need to call BeginInvoke. 40 if (this.InvokeRequired) 41 { 42 // Pass the same function to BeginInvoke, 43 // but the call would come on the correct 44 // thread and InvokeRequired will be false. 45 this.BeginInvoke(new SetLabelTextDelegate(SetLabelText), 46 new object[] { myClass }); 47 48 return; 49 } 50 51 label1.Text = myClass.Name; 52 } 53 54 private delegate void SetLabelTextDelegate(MyClass myClass); 55 } 56 57 public class myClassCollection 58 { 59 [Filed]#region [Filed] 60 61 private IList<MyClass> myClassItems = new List<MyClass>(); 62 63 #endregion 64 65 [Constructor]#region [Constructor] 66 67 public myClassCollection() 68 { 69 for (int i = 0; i < 100; i++) 70 { 71 MyClass my = new MyClass(); 72 my.Name = "Nmae" + new Random().Next(100).ToString(); 73 my.Age = new Random().Next(100); 74 myClassItems.Add(my); 75 Thread.Sleep(10);//加了这句和不加这句,结果不一样。 76 } 77 } 78 79 #endregion 80 81 [property]#region [property] 82 83 public IList<MyClass> MyCollection 84 { 85 get 86 { 87 return myClassItems; 88 } 89 set 90 { 91 myClassItems = value; 92 } 93 } 94 95 #endregion 96 97 [index]#region [index] 98 99 public MyClass this[int index]100 {101 get102 {103 return (MyClass)myClassItems[index];104 }105 }106107 #endregion108109 GetEnumerator#region GetEnumerator110111 public IEnumerator GetEnumerator()112 {113 foreach (MyClass c in myClassItems)114 {115 yield return c;116 }117 }118119 #endregion120121 }122123 public class MyClass124 {125 [Constructor]#region [Constructor]126 #endregion127128 [Filed]#region [Filed]129130 private string _name;131132 private int _age;133134 #endregion135136 [property]#region [property]137138 public string Name139 {140 get141 {142 return _name;143 }144 set145 {146 _name = value;147 }148 }149150 public int Age151 {152 get153 {154 return _age;155 }156 set157 {158 _age = value;159 }160 }161162 #endregion163 }164165} /Files/nanshouyong326/CSharpGeriac.rar 程序中我加入注释的一句:Thread.Sleep(10);//加了这句和不加这句,结果不一样。高手可以测试下。我不明白为什么,,请高手指点!!!