在WinForm中,直接使用自己创建的线程去使用窗体中的控件,是不安全的,不允许这样操作,以用委托的方式进行处理,但是可以屏蔽掉:
Control.CheckForIllegalCrossThreadCalls = false; //这句话就是说获取或设置一个值,该值是否捕获对错误线程的调用
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();
}
新开线程修改主线程控件属性为什么要报错?
答:vs2003时,这种情况是不报错的,vs2005时,微软不建议这样处理。
方法一:VS2003兼容方法处理,如下:
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
方法二:微软建议作法,使用委托来修改主线程控件的属性。
Tags:
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。