2012-09-29 811 views
1

从我的形式运行下面的方法时,我得到了以下错误消息Access to the port 'COM5' is denied.。我尝试从我的设备管理器的端口设置输入正确的波特率9600。我也尝试通过Portmon访问设备,但是有一个错误阻止了我的连接。任何替代解决这个问题?访问端口“COM5”被拒绝

 //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); 
     } 
+2

你想访问什么类型的设备,以确保没有其他人正在尝试使用该设备。 –

+1

如果程序崩溃,有时端口会卡住,需要重新启动。 – Brad

+2

该端口已被另一个进程打开。或者你的,不要点击那个按钮两次。 –

回答

2

您需要包装中使用的SerialPort在一个using statement或实施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. 
} 
+0

谢谢!你可以多描述一下这段代码吗?它适合哪里,它做什么? –

+0

感谢Johan,您是否会在我发布的方法之前放置using语句以确保comport不被使用? –

+0

它看起来像你的端口是一个类变量,所以IDisposable更适合你的情况。 调用port.Dispose()在Dispose方法见链接实现了IDisposable:http://www.codeproject.com/Articles/15360/Implementing-IDisposable-and-the-Dispose-Pattern-P –