我有一個代碼,其是這樣的:如何避免GUI凍結?
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....";
}
}
上述代碼是讀取一個傳感器即datarec = serialport_FT(0,1);函數爲GUI端提供了一個傳感器輸出,後面會用紅色\綠色描述ovalShapeX(1-6)
問題:datarec = serialport_FT(0, 1);
這個函數需要liltime,因此GUI會凍結,直到那個時候如何避免這種情況?
我試過使用後臺工作器,但沒有得到在哪裏把整個過程 也遇到了交叉線程操作錯誤,當它去到ovalShape並改變它的屬性。
我沒有收到在後臺使用什麼功能的一部分,何時何地回到第一線
請幫我使用的BackgroundWorker或使用調用,如果我必須使用線程
在後臺線程中調用serialport_FT() - 請參閱http://stackoverflow.com/search?q=c%23+gui+background – Slugart
使用backgroundworker,將'serialport_FT(0,1)'放入'DoWork()'並將'if(datarec){...}'放入'Completed()'事件中。 –
爲了避免出現交叉線程異常,請執行以下操作:http:// stackoverflow。com/a/1136406/400303 – Mohammad