我有DataReceviedHandler,即从Rx终端读取数据。 我想在Rx(从DataReceviedHandler)获取数据后更改radioButton的状态但是我收到此错误:“跨线程操作无效:控制'radioButton3'从线程以外的线程访问创建于。” 我该怎么做才能解决?
谢谢, 盎司
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
m_ser.GetType();
m_ser.PortName = "COM28";
m_ser.BaudRate = 115200;
m_ser.Open();
m_ser.ReadTimeout = 500;
m_ser.WriteTimeout = 500;
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void DataReceviedHandler(object sender, SerialDataReceivedEventArgs e)
{
byte[] m_rxUSBbuff = new byte[500];
SerialPort sptemp = (SerialPort)sender;
UInt16 rxbuffLength = (UInt16)m_ser.BytesToRead;
byte[] rxBuff = new byte[rxbuffLength];
try
{
rxbuffLength = (UInt16)sptemp.Read(rxBuff, 0, sptemp.BytesToRead);
}
catch (System.IO.IOException)
{
Console.WriteLine("Faild to Read from serial InputBuffer");
return;
}
int i;
int m_rxUSBLstMsgLength;
m_rxUSBLstMsgLength = (UInt16)rxbuffLength;
for (i = 0; i < m_rxUSBLstMsgLength; i++)
{
m_rxUSBbuff[i] = rxBuff[i];
}
switch (m_rxUSBbuff[0])
{
case 1:
radioButton1.Checked = true;
break;
case 2:
radioButton2.Checked = true;
break;
case 4:
radioButton3.Checked = true;
break;
case 8:
radioButton4.Checked = true;
break;
case 16:
radioButton5.Checked = true;
break;
default:
break;
}
}
private void CheckLeds_Click(object sender, EventArgs e)
{
byte[] txb = new byte[1] { 0xf2 };
m_ser.Write(txb, 0, 1);
}
}
答案 0 :(得分:1)
数据到达后台线程,也是调用事件处理程序的位置。不允许您从其创建的线程(UI线程)之外的线程修改UI元素。如果您搜索stackoverflow,那么您将找到如何执行此操作的大量答案。在Winforms中,您需要使用InvokeRequired
,在WPF中,您需要调用UI调度程序。
此问题的答案之一包含一大堆类似问题的链接:Cross-thread operation not valid
答案 1 :(得分:0)