c#异步入门
能用异步,就不要用线程,感觉线程要是控制不好,比较容易出问题
1 //要异步完成的方法
2 private void AddRadNum()
3 {
4 while(true)
5 {
6 Random r = new Random();
7 lstNum.Items.Add( r.Next(100,1000));
8 Thread.Sleep(500);
9 }
10 }
11
12 //定义一个委托
13 private delegate void delegateAddRadNum();
14
15 private void btnOK_Click(object sender, System.EventArgs e)
16 {
17 //实例化委托
18 delegateAddRadNum da = new delegateAddRadNum(AddRadNum);
19 //开始异步
20 IAsyncResult iar = da.BeginInvoke(null, null);
21 }
2 private void AddRadNum()
3 {
4 while(true)
5 {
6 Random r = new Random();
7 lstNum.Items.Add( r.Next(100,1000));
8 Thread.Sleep(500);
9 }
10 }
11
12 //定义一个委托
13 private delegate void delegateAddRadNum();
14
15 private void btnOK_Click(object sender, System.EventArgs e)
16 {
17 //实例化委托
18 delegateAddRadNum da = new delegateAddRadNum(AddRadNum);
19 //开始异步
20 IAsyncResult iar = da.BeginInvoke(null, null);
21 }