我有一个私有函数,它创建一个新的串行端口并打开它。有时,我会收到“安全句柄已关闭”异常,这会终止应用程序。现在,我一直在阅读一些可选的修复程序,并想从您的经验中了解,我的代码中真正的问题可能是什么。1)需要在_serialPort
这个私有函数的范围之外定义变量。2) 串口的 readTimeout 属性不应该是无限的。3) 上面的 using 语句处理我的portName
变量。
SerialPort _serialPort;
string[] devices =
ConfigurationManager.AppSettings["GasAnalyzerDeviceName"].Split(',');
string portName;
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"))
{
portName = (from p in searcher.Get().Cast<ManagementBaseObject>()
let c = "" + p["Caption"]
where c != null
where devices.Any(d => c.Contains(d.Trim()))
from pn in SerialPort.GetPortNames()
where c.Contains(pn)
select pn).FirstOrDefault();
}
if (portName == null)
portName = ConfigurationManager.AppSettings["GasAnalyzerPortName"];
if (portName == null)
throw new Exception("Gas port not found");
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Set Serial port properties
_serialPort.PortName = portName;
_serialPort.BaudRate = 115200;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = Timeout.Infinite;//1200;
_serialPort.WriteTimeout = 1200;
谢谢!