[英]Access to the port 'COM5' is denied
我收到以下錯誤消息Access to the port 'COM5' is denied.
從我的表單運行下面的方法時。 我嘗試從設備管理器的端口設置中輸入正確的波特率 9600。 我也嘗試通過 Portmon 訪問設備,但有一個錯誤阻止我連接。 有什么辦法可以解決這個問題嗎?
//Fields
List<string> myReceivedLines = new List<string>();
//subscriber method for the port.DataReceived Event
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
while (sp.BytesToRead > 0)
{
try
{
myReceivedLines.Add(sp.ReadLine());
}
catch (TimeoutException)
{
break;
}
}
}
protected override void SolveInstance(IGH_DataAccess DA)
{
string selectedportname = default(string);
DA.GetData(1, ref selectedportname);
int selectedbaudrate = default(int);
DA.GetData(2, ref selectedbaudrate);
bool connecttodevice = default(bool);
DA.GetData(3, ref connecttodevice);
port.DtrEnable = true; //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)
port.Open(); //Open the port
if (!(port.IsOpen == true)) port.Open();
if (connecttodevice == true)
{
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
DA.SetDataList(0, myReceivedLines);
}
您需要將 SerialPort 的使用包裝在using 語句中或實現IDisposable
// Dispose() calls Dispose(true)
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// The bulk of the clean-up code is implemented in Dispose(bool)
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (_serialPort != null)
{
_serialPort.Dispose();
_serialPort = null;
}
}
// free native resources if there are any.
}
我的串口監聽器有問題,主進程卡住了 - 因為它是同步的。 進程,通過創建一個線程和一個計時器來解決
try
{
if (_serialConnection.IsOpen) _serialConnection.Close();
_serialConnection.Open();
Thread newThread = new Thread((obj) =>
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += (sender, e) =>
{
_slave.Listen();
};
timer.Enabled = true;
timer.Start();
});
newThread.IsBackground = true;
newThread.Start();
}
catch (Exception ex)
{
throw ex;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.