[英]Serial Comms C#
I am writing a C# application to communicate via serial to a microcontroller. 我正在编写一个C#应用程序,通过串口与微控制器进行通信。 I have a few questions on how to handle received messages.
关于如何处理收到的消息,我有几个问题。 Below is the code that I am using at the moment, It received the messages perfectly fine, but I cannot update the Form, or store the data anywhere outside of this method (because it is in another thread).
下面是我目前正在使用的代码,它收到的消息完全正常,但是我无法更新表单,或者将数据存储在此方法之外的任何位置(因为它在另一个线程中)。
com.DataReceived += new SerialDataReceivedEventHandler(OnReceived);
public void OnReceived(object sender, SerialDataReceivedEventArgs c) // This is started in another thread...
{
com.DiscardOutBuffer();
try
{
test = com.ReadExisting();
MessageBox.Show(test);
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
When I attempt to alter the Form, or call another method from here this is the error message I receive: "Cross Thead operation not valid". 当我尝试更改表单或从此处调用另一个方法时,这是我收到的错误消息:“Cross Thead操作无效”。
I would like to be able to display the information elsewhere or even better yet place it into an array to later be stored as a file. 我希望能够在其他地方显示信息,甚至更好地将信息放入数组中以便以后存储为文件。 Is there any way I can do this?
有什么方法可以做到这一点吗?
Thanks again! 再次感谢!
You need to invoke on the main thread using Invoke
or BeginInvoke
: 您需要使用
Invoke
或BeginInvoke
在主线程上Invoke
:
public void OnReceived(object sender, SerialDataReceivedEventArgs c)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new EventHandler<SerialDataReceivedEventArgs>(OnReceived), sender, c);
return;
}
com.DiscardOutBuffer();
try
{
test = com.ReadExisting();
MessageBox.Show(test);
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
Or you can factor out part of the event handler (like showing a message box) and invoke that instead. 或者您可以将事件处理程序的一部分(如显示消息框)分解出来并调用它。
The issue you have is that you are trying to update the UI from an non-ui thread. 您遇到的问题是您正在尝试从非ui线程更新UI。 What you need to do is invoke your
MessageBox
call on the UI thread. 您需要做的是在UI线程上调用
MessageBox
调用。
Something like: 就像是:
public void OnReceived(object sender, SerialDataReceivedEventArgs c) // This is started in another thread...
{
com.DiscardOutBuffer();
try
{
test = com.ReadExisting();
SetValue(test);
}
catch (Exception exc)
{
SetValue(exc.ToString());
}
}
delegate void valueDelegate(string value);
private void SetValue(string value)
{
if (this.InvokeRequired)
{
this.Invoke(new valueDelegate(SetValue),value);
}
else
{
MessageBox.Show(value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.