2012-09-29 816 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 –