c# - "Cross thread operation not valid"..在串行端口上读取数据时

标签 c# winforms serial-port multithreading

在 Windows 窗体应用程序中,在主窗体加载时,我设置了一个串行端口并开始读取它。目的是,当我在串口上收到一些数据时,我想打开另一个与数据相关的表单。

所以我使用串口的DataReceived事件处理程序。

  void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

            string str = this.serialPort1.ReadLine();


                if (!string.IsNullOrEmpty(str))
                {


                    Main.Instance.customerData = new CustomerData(str);
                    Main.Instance.customerData.MdiParent = Main.Instance;  //Exeption received at this point
                    Main.Instance.customerData.Disposed += new EventHandler(customerData_Disposed);

                    Main.Instance.customerData.Show();


                }

        }

但是当我尝试在事件处理程序中打开表单时,它给我一个 InvalidOperationExeption 提示: “跨线程操作无效:从创建它的线程以外的线程访问控制“Main”。”

我尝试删除代码行: Main.Instance.customerData.MdiParent = Main.Instance; 然后就可以正常工作了。但还必须分配 mdiparent 才能将其作为子窗体打开。

有什么建议可以解决这个问题吗?

最佳答案

在主窗体上使用 Invoke 方法。您必须将控制权传递给主窗体才能与其交互。事件处理程序在后台线程上触发。

以下是一些可能有效的示例代码:

void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string str = this.serialPort1.ReadLine();
    if (!string.IsNullOrEmpty(str))
    {
        ShowCustomerData(str);
    }   

}

private delegate void ShowCustomerDataDelegate(string s);

private void ShowCustomerData(string s)
{
    if (Main.Instance.InvokeRequired)
    {
        Main.Instance.Invoke(new ShowCustomerDataDelegate(ShowCustomerData), s);
    }
    else
    {

        Main.Instance.customerData = new CustomerData(str);
        Main.Instance.customerData.MdiParent = Main.Instance;  //Exeption received at this point
        Main.Instance.customerData.Disposed += new EventHandler(customerData_Disposed);

        Main.Instance.customerData.Show();
    }
}

关于c# - "Cross thread operation not valid"..在串行端口上读取数据时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5468039/

相关文章:

c# - 来自所选联系人的 Outlook 信息

C# 代码不能 "see"我的 C++ dll 中的方法

c# - 面板不会停靠在我希望它们在 winforms 中的位置

vb.net - VB流行颜色选择器

c++ - 如何在 Linux 上通过 C++ 串行接口(interface)与 Arduino 通信?

c# - 串口数据接收多次触发

Linux,串口,非缓冲模式

c# - 修改edmx模板文件

c# - WCF Windows 服务 - 长操作/回调调用模块

c# - 为什么 if 语句有效但 switch 语句无效