百度空间 | 百度首页 
 
查看文章
 
线程间操作无效: 从不是创建控件“xxx”的线程访问它
2009年10月30日 星期五 15:44

在WinForm中,直接使用自己创建的线程去使用窗体中的控件,是不安全的,不允许这样操作,以用委托的方式进行处理:


        delegate void WriteLabelText(string str, Color color);

        private void showSqlConnResult(string msg, Color color)
        {
            this.labelSqlConnStatus.Text = msg;
            this.labelSqlConnStatus.ForeColor = color;
            this.buttonTestSqlConn.Enabled = true;
        }

        private void threadTestConn()
        {
            string result = "连接数据库成功。";
            Color color = Color.Green;
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this.textBoxSqlConnString.Text.Trim());
            try
            {
                conn.Open();
                conn.Close();
            }
            catch (Exception E)
            {
                result = E.Message;
                color = Color.Red;
            }
            WriteLabelText wt = new WriteLabelText(showSqlConnResult);
            this.Invoke(wt, result, color);
        }

        private void buttonTestSqlConn_Click(object sender, EventArgs e)
        {
            this.buttonTestSqlConn.Enabled = false;
            this.labelSqlConnStatus.ForeColor = Color.Blue;
            this.labelSqlConnStatus.Text = "正在测试连接数据库……";
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.threadTestConn));
            thread.Start();

        }


类别:.net技术 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu