这里只是一个小问题,这个代码我成功地从我的串口获取数据但是当我想在标签中看到这些数据时,我得到了这个: System.InvalidOperationException:'调用线程无法访问此对象,因为另一个线程是所有者'。 我不确定调度员是什么以及如何使用它。你能解释一下吗?
public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
//init serialport comport
SerialPort comport = (SerialPort)sender;
// Shortened and error checking removed for brevity...
if (!comport.IsOpen) return;
int bytes = comport.BytesToRead;
byte[] buffer = new byte[bytes];
comport.Read(buffer, 0, bytes);
HandleSerialData(buffer, comport);
}
public void HandleSerialData(byte[] respBuffer, SerialPort comport)
{
StringBuilder hex = new StringBuilder(respBuffer.Length * 2);
foreach (byte b in respBuffer)
hex.AppendFormat("{0:x2}", b);
string hex2 = hex.ToString();
hex2 = hex2.Substring(22, 8);
EnOcean_Label.Dispatcher.CheckAccess();
EnOcean_Label.Content = hex2;
}**
答案 0 :(得分:1)
试试这个。
public void HandleSerialData(byte[] respBuffer, SerialPort comport)
{
StringBuilder hex = new StringBuilder(respBuffer.Length * 2);
foreach (byte b in respBuffer)
hex.AppendFormat("{0:x2}", b);
string hex2 = hex.ToString();
hex2 = hex2.Substring(22, 8);
//EnOcean_Label.Dispatcher.CheckAccess();
Dispatcher.BeginInvoke((Action)(()=>{EnOcean_Label.Content = hex2;}));
}
答案 1 :(得分:0)
你必须在UI线程上调用它。
您正在调用EnOcean_Label.Dispatcher.CheckAccess();
,但这还不够,因为它会告诉您是否与调度程序关联的线程。
最好调用Dispatcher.Invoke
,这将保证代码将在Dispatcher线程上运行。