使用C#在串口数据接收方法中并行运行两个方法 [英] Run two methods in parallel in serial port data received method using C#

查看:696
本文介绍了使用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#在串口数据接收方法中并行运行两个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆