IF you want to update some information in windows form control from another thread please use the following class. 🙂
IF you receive the error : “Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on ….” use the following class. 🙂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public static class CrossThreadUtility { public static void InvokeControlAction<t>(t cont, Action<t> action) where t : Control { try { if (cont.InvokeRequired) { cont.Invoke(new Action<t, Action<t>>(InvokeControlAction), new object[] { cont, action }); } else { action(cont); } } catch { } } } |
This class can be used from .Net 3.5 version.
How to use it:
1 2 3 4 5 6 7 8 9 10 |
// for labels CrossThreadUtility.InvokeControlAction<Label>(frm.lblSoftwareStatus_Value, lbl => lbl.Text = Convert.ToString(status.SoftwareStatusPrinter.SoftwareVersion, CultureInfo.InvariantCulture)); // for text boxes CrossThreadUtility.InvokeControlAction<TextBox>(frm.txtInformationLog, lbl => lbl.Text = String.Format("SendData -> \r\nHeader {0} \r\nData {1}", header, data)); // for buttons CrossThreadUtility.InvokeControlAction<Button>(frm.btnTotal2, btn=> btn.BackColor = SystemColors.Control); CrossThreadUtility.InvokeControlAction<Button>(frm.btnTotal2, btn => btn.Refresh()); // for windows forms CrossThreadUtility.InvokeControlAction<frmDeviceCommunicationForm>((frmDeviceCommunicationForm)form, frm => frm.Close()); CrossThreadUtility.InvokeControlAction<frmDeviceCommunicationForm>((frmDeviceCommunicationForm)form, frm => frm.Dispose()); |
I consider that is a good class, to use it in multi threaded aplications.
Don’t forget to modify it as you want. 🙂