这是我的程序,它从端口读取来电显示数据的数据。但是我希望一旦它获得了它应该停止监听端口并读取更多数据的数字。并执行异常编写的任务。但是,当我强行尝试退出事件时,即使它没有工作,但是当我设置超时时也不会离开..我该怎么办请告诉我。
bool _continue = true;
string message = string.Empty;
string number = string.Empty;
private void serialPort_DataNewReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
if (_continue)
{
SerialPort sp = (SerialPort)sender;
message = sp.ReadExisting();
if (message.Contains("MESG"))
{
string[] strFirstStep = Regex.Split(message, "\r\nNMBR =");
string[] strLastStep = Regex.Split(strFirstStep[1], "\r\n");
number = strLastStep[0];
_continue = false;
}
}
else throw new TimeoutException();
}
catch (TimeoutException t)
{
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
}
答案 0 :(得分:1)
您需要从串口对象
中删除该事件serialPort.DataReceived -= serialPort_DataNewReceived;
答案 1 :(得分:1)
为什么DataReceived
中有超时异常?也许你需要这样的东西:
bool _continue = true;
string message = string.Empty;
string number = string.Empty;
private void serialPort_DataNewReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// stop listening (by ignoring call)
if (!_continue)
return;
// proceed
SerialPort sp = (SerialPort)sender;
message = sp.ReadExisting();
if (message.Contains("MESG"))
{
string[] strFirstStep = Regex.Split(message, "\r\nNMBR =");
string[] strLastStep = Regex.Split(strFirstStep[1], "\r\n");
number = strLastStep[0];
_continue = false;
// do a work if number is received
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
要处理超时(当您暂时不接收数据时),您可以创建一个计时器,该计时器将在收到数据时重置。如果计时器未及时复位,则其触发事件将触发,这意味着 - 超时。