這是我的代碼。在這段代碼中,我不時每秒位叫我越來越訪問端口'COM1'被時間控制器拒絕
誤差補償端口訪問被拒絕
我經過5次來電此。
using (SerialPort port = new SerialPort(serialPortName))
{
if (port.IsOpen)
{
port.Close();
port.Dispose();
}
port.BaudRate = 19200;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.Two;
port.Open();
// create modbus master
IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
byte slaveId = Convert.ToByte(txtSlaveId.Text.Trim());
ushort startAddress = Convert.ToUInt16(StartAddress);
ushort numRegisters = Convert.ToUInt16(NumberofRegisters);
SystemLog systemLog = new SystemLog();
systemLog.SlaveId = txtSlaveId.Text.Trim();
systemLog.VariableName = VariableName;
systemLog.ReadStartTime = DateTime.Now;
switch (Type)
{
case "CO":
bool[] status = master.ReadCoils(slaveId, startAddress, numRegisters);
for (int j = 0; j < numRegisters; j++)
{
systemLog.ReadEndTime = DateTime.Now;
systemLog.ReadAddress = Convert.ToString(Convert.ToInt32(StartAddress) + j);
systemLog.ReadType = (int)PLCReadType.COIL;
systemLog.ReadValue = Convert.ToString(status[j]);
}
break;
case "IR":
ushort[] inputRegister = master.ReadInputRegisters(slaveId, startAddress, numRegisters);
for (int j = 0; j < numRegisters; j++)
{
systemLog.ReadEndTime = DateTime.Now;
systemLog.ReadAddress = Convert.ToString(Convert.ToInt32(StartAddress) + j);
systemLog.ReadType = (int)PLCReadType.COIL;
systemLog.ReadValue = Convert.ToString(inputRegister[j]);
}
break;
case "HR":
ushort[] holdingRegister = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);
for (int j = 0; j < numRegisters; j++)
{
systemLog.ReadEndTime = DateTime.Now;
systemLog.ReadAddress = Convert.ToString(Convert.ToInt32(StartAddress) + j);
systemLog.ReadType = (int)PLCReadType.COIL;
systemLog.ReadValue = Convert.ToString(holdingRegister[j]);
}
break;
}
systemLogArray[i] = systemLog;
port.Close();
port.Dispose();
}
程序員過於渴望關閉()串口。這與SerialPort類的設計方式不兼容。也不允許另一個程序竊取你的端口並讓你的程序隨機崩潰。 MSDN文檔SerialPort.Close警告這一點,有一個工作線程需要退出之前,端口再次可用,生成事件。究竟需要多長時間是不可預測的。唯一可行的方法是在啓動程序時打開該端口,直到它結束才關閉端口。 –
@HansPassant你應該發佈這個答案我想?這聽起來很好,被upvoted。 –