Getting cross thread error trying to update a row in datagridview from Backgroundworker process RunWorkerCompleted event.
I have a separate class where i am doing long running work in the backgroundworker and when complete trying to update the datagridview from the result. Event fires but get a cross tread exception.
Fails when i try to update the gridview here DataGVhome.Rows[rowIndex].Cells["AlertInfo"].Value = alertMsg.SensorAlert;
From reading numerouos articles and others having issues this is supposed to work i.e. handling the DGV row update once the backgroundworker completed event fires.
private void MSbackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string hitfile = (string)e.Argument;
e.Result = _MassSpec.ParseMassFile(hitfile);
}
catch(Exception ex)
{
log.Error("Error in MDShomeForm:MSbackgroundWorker_DoWork - " + e.Result.ToString() + " " + ex.Message + Environment.NewLine);
}
}
private void MSbackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
MetroMessageBox.Show(this, "Error in Mass RunWorker = " + e.Error.Message);
}
else if (e.Cancelled)
{
// handle cancellation
MetroMessageBox.Show(this, "Mass RunWorker was Cancelled = " + e.Error.Message);
}
else
{
AlertMsg alertMsg = (AlertMsg)e.Result;
// Test it for hit and update grid in the UI thread
try
{
string searchValue = "";
int rowIndex = -1;
//update the gridview for this sensor
searchValue = alertMsg.SensorType;
foreach (DataGridViewRow row in DataGVhome.Rows)
{
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
break;
}
}
if (rowIndex > -1)
{
// update the L1 Alert for this sensor at rowIndex
DataGVhome.Rows[rowIndex].Cells["AlertInfo"].Value = alertMsg.SensorAlert;
//dataGVhome.Rows[rowIndex].Cells["AlertIndicator"].Value = alertMsg.SensorAlert;
switch (alertMsg.SensorAlertInd)
{
case (int)StandardVals.AlertInds.Green:
DataGVhome.Rows[rowIndex].Cells["AlertIndicator"].Value = "Green";
DataGVhome["AlertIndicator", rowIndex].Style.BackColor = Color.LightGreen;
break;
case (int)StandardVals.AlertInds.Yellow:
DataGVhome.Rows[rowIndex].Cells["AlertIndicator"].Value = "Yellow";
DataGVhome["AlertIndicator", rowIndex].Style.BackColor = Color.Yellow;
break;
case (int)StandardVals.AlertInds.Red:
DataGVhome.Rows[rowIndex].Cells["AlertIndicator"].Value = "Red";
DataGVhome["AlertIndicator", rowIndex].Style.BackColor = Color.Red;
break;
}
DataGVhome.Update();
}
}
catch (Exception ex)
{
log.Error("Error in MDShomeForm:MSBackgroundWorkerCompleted - " + ex.Message + Environment.NewLine);
}
}
// general cleanup code, runs when there was an error or not.
}
I log the exception here 2019-06-26 17:16:18,564 ERROR MDS_Command_Application.MDShomeForm - Error in MDShomeForm:MSBackgroundWorkerCompleted - Cross-thread operation not valid: Control 'DataGVhome' accessed from a thread other than the thread it was created on.