[英]Acces denied on com port c#
我一直在為機器編寫一些代碼。 它必須使用RS485通訊,並且我可以使用.net提供的常規串行通訊。
但是,由於硬件可能發生故障,因此我必須構建測試例程。 所以我寫了例程,重新檢測可用的命令。 這將使用其字符串名稱填充列表“ allComPorts”,然后使用數字向上鍵根據其可用端口的列表索引來選擇端口。 (是的,這聽起來有點復雜,但是由於其他原因,我使用了數字上下鍵進行選擇)。
問題在於此功能僅在第一次喚醒。 如果我再次調用該函數,則因為接縫已經打開,所以訪問被拒絕。 在各個地方都嘗試過RS485Port.Close(),但問題是如果尚未打開噴氣機,它就會崩潰(一個雞蛋問題)。
我打開通勤的代碼是這樣的
private void RS485Activate()
{
lblNoRS485Communication.Visible = false;
if (cmbRS485Port.Value != 0) // if 0 then there are no serial ports
{
//rs485Port is a global declared as > System.IO.Ports.SerialPort RS485Port;
RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]);
if (!RS485Port.IsOpen)
{
// RS485Port.Close();
// RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]);
RS485Port.BaudRate = 9600;
RS485Port.Parity = System.IO.Ports.Parity.None;
RS485Port.StopBits = System.IO.Ports.StopBits.One;
RS485Port.DataBits = 8;
RS485Port.Handshake = System.IO.Ports.Handshake.None;
RS485Port.RtsEnable = true;
RS485Port.Open(); <== it crashes here with access denied
}
}
else
{
MessageBox.Show("There is no COM port detected, the program will work but it cannot control any machinery", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
lblNoRS485Communication.Visible = true; // another warning
}
}
我不喜歡這樣的外觀,所以我希望有更好的方法。 但是,作為一種變通方法,現在使用嘗試捕獲構造首先嘗試關閉它(如果尚未初始化,則try-catch確實可以防止close()錯誤。嗯,我不喜歡這種解決方法,因此有更好的解決方案不客氣,我認為代碼不應該預料到並基於錯誤(或者現在可以使用.net嗎?)
//...
try
{ RS485Port.Close(); }
catch
{ }
RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]);
if (!RS485Port.IsOpen)
{
// RS485Port.Close();
// RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]);
RS485Port.BaudRate = 9600;
RS485Port.Parity = System.IO.Ports.Parity.None;
RS485Port.StopBits = System.IO.Ports.StopBits.One;
RS485Port.DataBits = 8;
RS485Port.Handshake = System.IO.Ports.Handshake.None;
RS485Port.RtsEnable = true;
RS485Port.Open();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.