很多优秀的程序员(包括很多优秀的 Stackoverflow 成员)都反对在Application.DoEvents()
任何情况下使用。实际上,它甚至得到了网络上大量文章的支持,例如这篇文章,关于 SO 的著名辩论,...
虽然,我被困在一个案例中,(我)认为DoEvents()
是唯一的出口(缺乏经验)。介绍就够了,让我们看一些编码。
我有一个“serialPort”组件通过串行通信与控制器连接,发送命令并等待其响应,仅此而已。
string response = "";
bool respFlag;
private string sendCommand(string command)
{
respFlag = false; //initialize respFlag
serialPort1.Write(command); // send the command
Stopwatch timer = Stopwatch.StartNew(); // start a timer
while(true)
{
// break from the loop if receive a response
if(respFlag) break;
// timeOut error if no response for more than 500msec
if(timer.ElapsedMilliseconds >= 500) break;
// here comes the UGLY part
Application.DoEvents();
}
return response;
}
在我的 serialPort 的 DataReceived 方法中,我读取了现有的响应并打破了循环
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
response = serialPort1.ReadExisting();
// set the flag to true to exit the infinite loop in sendCommand
respFlag = true;
}
不完全是这样,但这是一个示例代码,显示了我如何通过串行通信接收信息,你能告诉我我在哪里强迫自己陷入这个陷阱吗?