“跨线程操作无效". ..在串行端口上读取数据时 [英] "Cross thread operation not valid" .. while reading data on Serial Port
问题描述
在Windows窗体应用程序中,在主窗体加载时,我已经设置了一个串行端口并开始读取它.目的是,当我在串行端口上收到一些数据时,我想打开与该数据相关的另一种形式.
In a windows form application, on main form load, i have set a serial port and started reading it. The purpose is, as and when I receive some data on the serial port, I want to open another form related to the data.
因此,我使用串行端口的DataReceived事件处理程序.
So i use the DataReceived Event Handler of the serial port.
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'是从创建该线程的线程之外的线程访问的."
But when I try to open a form within the event handler it gives me an InvalidOperationExeption saying: "Cross-thread operation not valid: Control 'Main' accessed from a thread other than the thread it was created on."
我尝试删除代码行:
Main.Instance.customerData.MdiParent = Main.Instance;
然后就可以了但是也有必要分配mdiparent,以便将其作为子窗体打开.
I tried removing the code line :
Main.Instance.customerData.MdiParent = Main.Instance;
then it works fine. But its necessary also to assign the mdiparent in order to open it as a child form.
是否有解决此问题的建议?
Any suggestions to resolve this problem ?
推荐答案
在Main窗体上使用Invoke方法.您必须将控制权传递给Main表单才能与其进行交互.事件处理程序在后台线程上触发.
Use the Invoke method on the Main form. You have to pass control over to the Main form to interact with it. The event handler is triggered on a background thread.
以下一些可能有效的示例代码:
Here's some sample code that may work:
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();
}
}
这篇关于“跨线程操作无效". ..在串行端口上读取数据时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!