Kha*_*laf 2 c# multithreading serial-port
在串行端口通信解决方案之后,我实现了以下设计。我的代码用于与在同一台机器上侦听的串行端口实用程序应用程序com8进行通信,然后发回(我手动键入消息并按下按钮)com9
我主要这样做:
MyClass MyObj = new MyClass();
var message = MyObj.SendThenRecieveDataViaSerialPort("Test");
Run Code Online (Sandbox Code Playgroud)
然后在我的课堂上我有这个:
private static SerialPort MainSerialPort { get; set; } = new SerialPort();
private static string _ReceivedMessage;
private Thread readThread = new Thread(() => ReadSerialPort(ref _ReceivedMessage));
public string SendThenRecieveDataViaSerialPort(string _Message)
{
MainSerialPort = new SerialPort("com8", 9600);
MainSerialPort.ReadTimeout = 5000;
MainSerialPort.WriteTimeout = 5000;
MainSerialPort.Open();
readThread.Start(); // 1
try
{ // 2
MainSerialPort.WriteLine(_Message); // 3
readThread.Join(); // 6 - Console pops and waits
}
catch (TimeoutException ex)
{
Console.WriteLine("Exception in SendThenreceive");
}
return _ReceivedMessage;
}
private static void ReadSerialPort(ref string _message)
{
try
{ // 4
_message= MainSerialPort.ReadLine(); // 5
}
catch (TimeoutException ex)
{
// 7 - when time outs
}
}
Run Code Online (Sandbox Code Playgroud)
然而,它在第 7 步抛出错误:
{“操作已超时。”}
内部异常:空
你能告诉我哪里出错了吗?请并谢谢。
ReadLine 等待直到看到 SerialPort.NewLine 字符串。如果这没有在 SerialPort.ReadTimeout 内到达,则会抛出 TimeoutException。所以不要错过发送 NewLine!
这是没有 NewLine 的替代版本。
byte[] data = new byte[1024];
int bytesRead = MainSerialPort.Read(data, 0, data.Length);
_message = Encoding.ASCII.GetString(data, 0, bytesRead);
Run Code Online (Sandbox Code Playgroud)