Winform中子线程访问界面控件时被阻塞解决方案
时间:2014-04-29 16:24:47
收藏:0
阅读:365
public partial class WebData_Import : Form { //声明用于访问主界面的委托类型 public delegate void deleGetOrderdata(string info); //声明访问主界面委托类型的变量 public deleGetOrderdata OptGetOrderData; int CompanyID = 0; public WebData_Import() { InitializeComponent(); cmbCompany.Items.Insert(0, "公司001"); cmbCompany.Items.Insert(1, "公司002"); cmbCompany.SelectedIndex = 0; //实例化委托 OptGetOrderData = new deleGetOrderdata(ShowOperationInfo); } private void button1_Click(object sender, EventArgs e) { txtOperationInfo.Text = ""; switch (cmbCompany.SelectedIndex) { case 0: CompanyID = 001; break; case 1: CompanyID = 002; break; } //执行获取订单数据线程 Thread GetOrderDataThread = new Thread(new ThreadStart(ExecuteGetOrderData)); GetOrderDataThread.Start(); } /// <summary> /// 访问主界面的方法 /// </summary> /// <param name="ShowInfo"></param> private void ShowOperationInfo(string ShowInfo) { txtOperationInfo.Text += ShowInfo + "\r\n"; } private void ExecuteGetOrderData() { DataTable GetOrderData = new DataTable(); //使用BeginInvoke从子线程访问主界面,传入访问主界面的方法和参数 this.BeginInvoke(OptGetOrderData, "1、导入数据操作开始"); this.BeginInvoke(OptGetOrderData, "\r\n2、正在获取数据,请稍后..."); try { GetOrderData = GetOrderTable(CompanyID, Convert.ToDateTime(Sdate.Text), Convert.ToDateTime(Edate.Text)); if (GetOrderData == null) { throw new Exception("没有从远程服务获取到任何数据"); } this.BeginInvoke(OptGetOrderData, "\r\n3、已获取" + GetOrderData.Rows.Count + "条数据,正在执行往数据库插入操作..."); SQLDBHELPER help = new SQLDBHELPER(); int InsertCount = help.SqlInsertBuilder(GetOrderData); this.BeginInvoke(OptGetOrderData, "\r\n4、成功插入" + InsertCount + "条数据,正在执行存储过程请稍后..."); string ErrorMessage = help.exectrans(); if (string.IsNullOrEmpty(ErrorMessage.Trim())) { this.BeginInvoke(OptGetOrderData,"\r\n5、存储过程执行成功,所有操作均已成功执行完毕!"); } else { this.BeginInvoke(OptGetOrderData, "\r\n5、存储过程执行失败!失败原因:" + ErrorMessage); } } catch (Exception ex) { this.BeginInvoke(OptGetOrderData, "\r\n系统执行异常,异常原因:" + ex.Message); } } }
评论(0)