我有一个代码,其是这样的:如何避免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