使用C#在串口数据接收方法中并行运行两个方法

编程入门 行业动态 更新时间:2024-10-15 22:31:42
本文介绍了使用C#在串口数据接收方法中并行运行两个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

I am working on an application which receives data at every second from serial port.I want to call both functions simultaneously. Please note that each of function is independent of each other.One function is used to display data on chart and other function is used to log data into a file. I used following approach but, I found that they are not running in parallel. Can anyone help me, how to achieve this task in parallel?

我尝试过: private void serialPort1_DataReceived (对象发送者,System.IO.Ports.SerialDataReceivedEventArgs e) { RxString = serialPort1.ReadExisting(); this .BeginInvoke(new EventHandler(Display)); this.BeginInvoke(new EventHandler(LogFile)); }

What I have tried: private void serialPort1_DataReceived (object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { RxString = serialPort1.ReadExisting(); this.BeginInvoke(new EventHandler(Display)); this.BeginInvoke(new EventHandler(LogFile)); }

推荐答案

Invoke方法将执行移动到构造调用它的控件的线程 - UI线程。 由于DataReceived事件永远不会与UI在同一个线程上: SerialPort。 DataReceived Event(System.IO.Ports) [ ^ ] 从SerialPort对象接收数据时,在辅助线程上引发DataReceived事件。 因此,您可以通过使用BeginInvoke尽可能接近您想要的内容显示任务,并在以下情况后立即执行日志任务: The Invoke method moves the execution to the thread that constructed the control it is Invoked on - the UI thread. Since the DataReceived event is never on the same thread as the UI: SerialPort.DataReceived Event (System.IO.Ports)[^] "The DataReceived event is raised on a secondary thread when data is received from the SerialPort object." As a result, you can get as close as possible to what you want by using BeginInvoke on the Display task, and doing the log task immediately after: private void serialPort1_DataReceived (object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { RxString = serialPort1.ReadExisting(); this.BeginInvoke(new EventHandler(Display)); LogFile(); }

请注意,这并不能保证同时执行 - 这取决于系统的其余部分在做什么。 但我会将字符串传递给每个方法而不是使其成为全局参数。

Do note this doesn't guarantee simultaneous execution - that depends on what the rest of the system is doing. But I would pass the string to each method instead of making it a global parameter.

更多推荐

使用C#在串口数据接收方法中并行运行两个方法

本文发布于:2023-11-25 04:58:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   串口   两个   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!