C# 在主程序中使用来自串口的日期
C# use date from serial port in mainprogram
我需要从COM口读取数据。数据来自Arduino,需要通过C#程序解析并在主机PC上做一些事情。我可以读取数据,但只能使用无休止的 "while true" 循环。这会阻止要执行的表单和其他任务。所以目前它看起来像这样:
while (true) {
oneLine = myPort.ReadLine();
this.Invoke(new EventHandler(display_data_Event));
// TBD: add analysis of data from port
// TBD: execute according to data from Arduino
}
处理程序:
private void display_data_Event(object sender, EventArgs e)
{
string curr_time = DateTime.Now.ToString("h:mm:ss tt");
port_in_TextBox.AppendText(curr_time + " " + oneLine + "\n");
}
所以我可以将数据显示到文本框,但不能在我的主程序中使用它。
如何仅在事件发生时使用 "one line" 字符串,而不是 "while true"?
我尝试从处理程序调用函数 - 我猜它失败了,因为它是另一个线程。所以也许问题在于如何将字符串从一个线程共享到另一个线程。
我迷路了,这里是核心程序:
https://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.datareceived?view=netframework-4.8
现在,问题是您需要一个输入还是多个输入。如果是前者,添加 AutoResetEvent
这样主程序将被阻塞,读取数据将发出解除阻塞的信号。或者,如果有很多行,请在阅读每一行后立即在事件中添加 "main" 操作。
我需要从COM口读取数据。数据来自Arduino,需要通过C#程序解析并在主机PC上做一些事情。我可以读取数据,但只能使用无休止的 "while true" 循环。这会阻止要执行的表单和其他任务。所以目前它看起来像这样:
while (true) {
oneLine = myPort.ReadLine();
this.Invoke(new EventHandler(display_data_Event));
// TBD: add analysis of data from port
// TBD: execute according to data from Arduino
}
处理程序:
private void display_data_Event(object sender, EventArgs e)
{
string curr_time = DateTime.Now.ToString("h:mm:ss tt");
port_in_TextBox.AppendText(curr_time + " " + oneLine + "\n");
}
所以我可以将数据显示到文本框,但不能在我的主程序中使用它。
如何仅在事件发生时使用 "one line" 字符串,而不是 "while true"? 我尝试从处理程序调用函数 - 我猜它失败了,因为它是另一个线程。所以也许问题在于如何将字符串从一个线程共享到另一个线程。
我迷路了,这里是核心程序: https://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.datareceived?view=netframework-4.8
现在,问题是您需要一个输入还是多个输入。如果是前者,添加 AutoResetEvent
这样主程序将被阻塞,读取数据将发出解除阻塞的信号。或者,如果有很多行,请在阅读每一行后立即在事件中添加 "main" 操作。