另一端的設備突然斷開連接後,我無法重新連接到COM端口。 只有關閉並重新打開應用程序,我才能再次連接。丟失連接後重新連接到COM
這裏是我的連接功能:
public bool connectTurboPump()
{
try
{
if (TPumpSerialPort != null && TPumpSerialPort.IsOpen == true)
return true;
DataRow dr = tblTPump.Rows[0];
Types.Connection TPumpConnection = new Types.Connection();
TPumpConnection.PORT = dr["port"].ToString();
TPumpConnection.BAUD_RATE = Convert.ToInt32(dr["baud"]);
TPumpConnection.PARITY = (Parity)Enum.Parse(typeof(Parity), dr["parity"].ToString(), true);
TPumpConnection.DATA_BITS = Convert.ToInt32(dr["dataBits"]);
TPumpConnection.STOP_BITS = (StopBits)Enum.Parse(typeof(StopBits), dr["stopBits"].ToString(), true);
TPumpConnection.HANDSHAKE = (Handshake)Enum.Parse(typeof(Handshake), dr["handshake"].ToString(), true);
TPumpSerialPort = new SerialPort(TPumpConnection.PORT, TPumpConnection.BAUD_RATE, TPumpConnection.PARITY, TPumpConnection.DATA_BITS, TPumpConnection.STOP_BITS);
TPumpSerialPort.Handshake = TPumpConnection.HANDSHAKE;
TPumpSerialPort.Open();
TPumpSerialPort.NewLine = "\r";
TPumpSerialPort.ReadTimeout = 10000;
TPumpSerialPort.WriteTimeout = 10000;
if (TPumpSerialPort.IsOpen != true)
return false;
return true;
}
catch { return false; }
}
這裏是我重新連接功能:
public bool reconnectTurboPump(int attempts = 3)
{
try
{
if (TPumpSerialPort != null && TPumpSerialPort.IsOpen == true)
{
TPumpSerialPort.Close();
TPumpSerialPort.Dispose();
}
int i = 1;
while (true)
{
Log(string.Format("Reconnecting Turbo Pump attempt {0}", i));
if (connectTurboPump())
break;
if (i == attempts)
return false;
i++;
}
return true;
}
catch (Exception ex)
{
Log(string.Format("Could not reconnect to Turbo Pump: {0}", ex.Message));
return false;
}
}
真的很感激,如果有人可以幫助。
謝謝。
請看看這個鏈接:http://stackoverflow.com/questions/4369679/com-port-is-denied。我想你會找到幾個適用的建議。 – paulsm4 2012-08-09 19:59:44
如果將if(TPumpSerialPort!= null && TPumpSerialPort.IsOpen == true)'改爲'if(TPumpSerialPort!= null)',會發生什麼? – 2012-08-09 20:06:48
經過評估10+串口解決方案後,我只找到一個工作。你可以在這裏看到我的答案詳細信息:http://stackoverflow.com/a/8003897/362536我不知道這個問題是否適用於你,但如果是這樣,我建議檢查CommStudio。 – Brad 2012-08-09 20:07:03