我想在发送数据之前检查我的串口是否已经打开。
public static bool Send(SerialPortStream portStream, data)
{
try
{
if (!portStream.IsOpen)
{
portStream.Open();
}
if (portStream.IsOpen) // line 1973 returned error already
//opened
{
//build message and write on portstream
try
{
portStream.Write(message, 0, message.Length);
}
catch (Exception)
{
return false;
}
return true;
}
}
catch (Exception e)
{
}
return false;
}
但问题是属性类“IsOpen”捕获错误“串行端口已打开”并且没有发送数据。我不明白为什么 get 属性不能返回错误值。
编辑:我使用 RJCP.IO.Ports.SerialPortStream 类作为我的串口。在上面的代码之前,我只从一个这样的线程中获取端口的实例
public static bool Read(string port, ..data)
{
SerialPortStream portStream = null;
foreach (SerialPortStream S in portStreams)
{
if (S.PortName == port)
{
portStream = S;
break;
}
}
if (portStream != null)
{
if (Send(portStream))
{
return true;
}
}
return false;
}
这是一个例外:
System.InvalidOperationException: Serial Port already opened at RJCP.IO.Ports.SerialPortStream.Open(Boolean setCommState) at RJCP.IO.Ports.SerialPortStream.Open() at Program.Send(SerialPortStream portStream) in Program.cs:line 1973')