1

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);
        }
4

2 回答 2

2

您需要将 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.
}
于 2012-09-30T00:11:52.073 回答
0

我的串口监听器有问题,主进程卡住了——因为它是同步的。过程,通过创建一个线程和一个计时器来解决

                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;
            }
于 2021-10-17T18:35:04.993 回答