How to avoid freezing of GUI?
c#, freeze, multithreading, user-interface, winforms
Solution
You could do something like this:
toolStripStatusLabel1.Text = " Device Testing...";
positive = false;
clearsensors_gui();
datarec = false;
cmd = 04;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
// Will be run on background thread
args.Result = serialport_FT(0, 1);
};
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
bool result = (bool)args.Result;
if (result)
{
// Do your UI updates here
}
};
worker.RunWorkerAsync();
One improvement could be to combine `datarec` and `rec_data` as a Tuple in args.Result.
Problem
i have a code which is like this : ``` private void testToolStripMenuItem_Click(object sender, EventArgs e) { toolStripStatusLabel1.Text = " Device Testing..."; positive = false; clearsensors_gui(); datarec = false; cmd = 04; datarec = serialport_FT(0, 1); if (datarec) { char ab = Convert.ToChar(rec_data[1]); //MessageBox.Show("\n" + ab + "\n"); int cab = Convert.ToInt16(ab); int cabc1 = cab & 1; int cabc2 = cab & 2; int cabc3 = cab & 4; int cabc4 = cab & 8; int cabc5 = cab & 16; int cabc6 = cab & 32; if (cabc1 == 1) ovalShape1.FillColor = Color.Green; else ovalShape1.FillColor = Color.Red; if (cabc2 == 2) ovalShape2.FillColor = Color.Green; else ovalShape2.FillColor = Color.Red; if (cabc3 == 4) ovalShape3.FillColor = Color.Green; else ovalShape3.FillColor = Color.Red; if (cabc4 == 8) ovalShape4.FillColor = Color.Green; else ovalShape4.FillColor = Color.Red; if (cabc5 == 16) ovalShape5.FillColor = Color.Green; else ovalShape5.FillColor = Color.Red; if (cabc6 == 32) ovalShape6.FillColor = Color.Green; else ovalShape6.FillColor = Color.Red; toolStripStatusLabel1.Text = " Device Tested"; } else { toolStripStatusLabel1.Text = "Try Again or Communication With Device Failure...."; } } ``` the above code is to read a the sensors i.e datarec = serialport_FT(0, 1); function provides me a sensor output at the GUI side which'll be later depicted with red\green ovalShapeX(1-6) Question: `datarec = serialport_FT(0, 1);` this function takes liltime and so the GUI freezes till that time how to avoid this? i tried using background worker but didn't get where to put this whole process also encountered with cross-threaded operation error when it goes to ovalShape and changing its properties. I'm not getting what part of the function to be used in the background and where and when to get back to the 1st thread please help me to use backgroundworker or use invoke if i have to use Threading