使用 C# 从串行端口接收消息的线程无法工作
我正在使用串行端口接收消息。下面的函数在线程中运行。当我调试时,我发现线程运行正常。但“if (sp.IsOpen)”始终为 false,因此代码根本不在 IF 条件内执行。据说港口已关闭。
我的系统中将有多个串行端口,但我不知道哪个端口将接收消息。所以我需要监听一个线程中的所有端口。
我该如何解决这里的问题?
private void ListenerPorts()
{
log.Info("Listening Thread Started");
while (true)
{
//foreach (SerialPort sp in storeport)
foreach (SerialPort sp in comPortsList)
{
if (sp.IsOpen)
{
sp.ReadTimeout = readTimeoutInMs;
sp.WriteTimeout = writeTimeoutInMs;
try
{
string msg = sp.ReadLine();
this.GetMessageRichTextBox("Message : " + msg + "\n");
sp.WriteLine(sp.PortName);
if (msg.Contains("COM"))
{
// is AutoScan
receiverPortName = sp.ReadLine();
this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + msg + "\n");
}
else
{
//standalone is uppercase
ReceiverPortName = sp.ReadLine();
this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + ReceiverPortName + "\n");
}
}
catch (Exception ex)
{
// no data
System.Diagnostics.Debug.WriteLine(sp.PortName + " : " + ex.Message);
}
}
}
}
}
I am using Serial port to receive the messages. The below function is running in a thread. When i debug i find that the thread is running properly. But "if (sp.IsOpen)" is always false, due to which the code is not executing inside the IF condition at all. It says the Port is closed.
I will be having multiple serial ports in my system and i will not know, which port will receive the message. So i need to listen to all the ports in one Thread.
How can i solve my problem here ?
private void ListenerPorts()
{
log.Info("Listening Thread Started");
while (true)
{
//foreach (SerialPort sp in storeport)
foreach (SerialPort sp in comPortsList)
{
if (sp.IsOpen)
{
sp.ReadTimeout = readTimeoutInMs;
sp.WriteTimeout = writeTimeoutInMs;
try
{
string msg = sp.ReadLine();
this.GetMessageRichTextBox("Message : " + msg + "\n");
sp.WriteLine(sp.PortName);
if (msg.Contains("COM"))
{
// is AutoScan
receiverPortName = sp.ReadLine();
this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + msg + "\n");
}
else
{
//standalone is uppercase
ReceiverPortName = sp.ReadLine();
this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + ReceiverPortName + "\n");
}
}
catch (Exception ex)
{
// no data
System.Diagnostics.Debug.WriteLine(sp.PortName + " : " + ex.Message);
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的串口初始化代码在哪里?特别是
SerialPort.Open();
行?看看使用
从他们那里接收数据。
Where's your initialization code for the serial ports? And in particular the line
SerialPort.Open();
?Take a look at using
to receive the data from them instead.