|
Author: Jenny Nguyen
|
|
I have just got an error Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on when I try to execute a C# windows application. I have been trying to use multi-threading in my winform so that while it is perform a long process task my UI would get locked up. However after the task has finish and it try to update the UI I get an error.
System.Threading.Thread T1 = new System.Threading.Thread(FindFuncLoc); T1.Start();
To get around this I use the mothodInvoker and put all my UI update inside this delegate and my problem is solved. this.Invoke(new MethodInvoker(delegate { tlFuncLoc.DataSource = dtFuncLocsResult; tlFuncLoc.Update(); lblMessage.Visible = false; mpSearchProgress.Visible = false; })); return;
SAMPLE CODE:
private void btnSearch_Click(object sender, EventArgs e) { try { //Ensure that a Plant is select before the search can begin. if (cbPlant.ItemIndex >= 0) { lblMessage.Visible = true; mpSearchProgress.Visible = true;
System.Threading.Thread T1 = new System.Threading.Thread(FindFuncLoc); T1.Start();
//FindFuncLoc(); } else { MessageBox.Show("Please select a plant to begin the search."); } } catch (Exception ex) { lblMessage.Visible = true; mpSearchProgress.Visible = true; MessageBox.Show(ex.Message); } }
private void FindFuncLoc() {
if (InvokeRequired) { // after we've done all the processing,
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("prEntitySelectFilter"); dbCommand.CommandTimeout = Program.Timeout; db.AddInParameter(dbCommand, "searchString", DbType.String, txtSearch.Text); db.AddInParameter(dbCommand, "rootEntityID", DbType.Int32, cbPlant.GetColumnValue("RootEntityID")); DataTable dtFuncLocsResult = db.ExecuteDataSet(dbCommand).Tables[0];
this.Invoke(new MethodInvoker(delegate { tlFuncLoc.DataSource = dtFuncLocsResult; tlFuncLoc.Update(); lblMessage.Visible = false; mpSearchProgress.Visible = false; })); return; }
} Like this Tip? Leave a comment if come across other solutions.
Comments (4)
"
|