首页 新闻 会员 周边

System.Threading.Timer 的问题

0
[已解决问题] 解决于 2012-07-03 09:38

private void button1_Click(object sender, EventArgs e)

{

  System.Threading.Timer a = new System.Threading.Timer(q => {   this.listBox1.Items.Add("btn:" + i++); }, null, 1000, 5000);

}

 static int i = 0; //全局变量

点击button时为什么一点击窗口就关闭了

koi的主页 koi | 初学一级 | 园豆:4
提问于:2012-07-02 15:11
< >
分享
最佳答案
1

把代码贴全了。你这代码编译都不过的。 i 是哪里来的。

奖励园豆:5
水牛刀刀 | 大侠五级 |园豆:6350 | 2012-07-02 16:28

全局变量i static int i = 0;

koi | 园豆:4 (初学一级) | 2012-07-02 16:29

@koi: 这是因为System.Threading.Timer是在线程池里(也就是说非UI线程)执行你的 this.listBox1.Items.Add 方法去修改UI的,这样是不允许的,因此抛出异常终止了程序。正确的做法是:

System.Threading.Timer a = new System.Threading.Timer(q =>
 {
    this.listBox1.Invoke(new Action(() => this.listBox1.Items.Add("btn:" + i++)));
 }, null, 1000, 5000);
水牛刀刀 | 园豆:6350 (大侠五级) | 2012-07-02 16:44
其他回答(1)
0

支持楼上的!!

Angkor--:-- | 园豆:1086 (小虾三级) | 2012-07-03 00:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册