C# 使用c从串行端口接收消息的线程不工作#
我正在使用串行端口接收消息。下面的函数正在线程中运行。调试时,我发现线程运行正常。但是“if(sp.IsOpen)”始终为false,因此代码根本没有在if条件内执行。上面说港口关闭了 我的系统中将有多个串行端口,我不知道哪个端口将接收消息。所以我需要监听一个线程中的所有端口 我怎样才能在这里解决我的问题C# 使用c从串行端口接收消息的线程不工作#,c#,serial-port,C#,Serial Port,我正在使用串行端口接收消息。下面的函数正在线程中运行。调试时,我发现线程运行正常。但是“if(sp.IsOpen)”始终为false,因此代码根本没有在if条件内执行。上面说港口关闭了 我的系统中将有多个串行端口,我不知道哪个端口将接收消息。所以我需要监听一个线程中的所有端口 我怎样才能在这里解决我的问题 private void ListenerPorts() { log.Info("Listening Thread Started"); whil
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);
}
}
}
}
}
串行端口的初始化代码在哪里?尤其是行
SerialPort.Open()代码>
看看如何使用
SerialPort.DataReceived +=
new SerialDataReceivedEventHandler(SerialDataReceivedEventHandler);
而是从他们那里接收数据。那么,这是否意味着我需要打开系统中的所有端口来接收消息?是的。请看,您可以为每个端口使用一个单独的线程(而不是DataReceived事件处理程序),但仍然需要打开端口才能使用它。