Last active
July 11, 2019 07:05
-
-
Save kgamecarter/3a0f009558fff4e96abe3e2d869aa717 to your computer and use it in GitHub Desktop.
SerialPort Retry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 建立多執行續工作 | |
Task.Run(() => | |
{ | |
retry: // 重試起點 | |
try | |
{ | |
port = new SerialPort(portName, 9600); | |
port.Open(); | |
string line; | |
while ((line = port.ReadLine()) != null) // 無限回圈讀取com資料 | |
{ | |
logger.Info("COM:" + JsonConvert.SerializeObject(line)); | |
line = line.Trim(); | |
switch (line) | |
{ | |
case "1": | |
// DO 1 | |
break; | |
case "2": | |
// DO 2 | |
break; | |
case "3": | |
// DO 3 | |
break; | |
default: | |
break; | |
} | |
} | |
port.Close(); | |
} | |
catch (Exception ex) // 連線失敗紀錄錯誤 | |
{ | |
logger.Error(ex.Message); | |
//MessageBox.Show(ex.Message.ToString()); | |
} | |
finally | |
{ | |
if (port != null) | |
port.Close(); | |
} | |
Thread.Sleep(5000); // 休息5秒 | |
goto retry; // 跳回重試起點 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment