1
我正在使用串口接收消息。下面的函数在一个线程中运行。当我调试我发现线程正常运行。但是“if(sp.IsOpen)”总是假的,因为代码在IF条件内根本不执行。它说港口已关闭。从串口接收消息的线程不能使用c#
我将在我的系统中有多个串行端口,我不知道哪个端口将收到消息。所以我需要听一个线程中的所有端口。
我该如何解决我的问题?
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);
}
}
}
}
}
那么,是否意味着我需要打开系统中用于接收消息的所有端口? – Anuya 2010-04-08 07:26:40
是的。请参阅http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx – 2010-04-08 15:25:21
您可以使用每个端口的单独线程(而不是DataReceived事件处理程序),但是您可以仍然需要打开端口才能使用它。 – 2010-04-08 15:27:01