我正在通过蓝牙从外部设备接收一些数据,并且我有一个事件处理程序,每当收到数据时都会触发。这是一个非常基本的应用程序,我在主页上有一个按钮,当按下按钮时,执行以下功能:
async void BLE_Function()
{
//some code to connect to the device
thermometerCharacteristic.ValueChanged += temperatureMeasurementChanged; //this is where I had a function to the event handler
await thermometerCharacteristic
.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
}
public void temperatureMeasurementChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
//Store the incoming bytes in a byte array called "temperatureData"
foreach (byte b in temperatureData)
{
Debug.WriteLine(b.ToString());
}
} 现在的问题是,我希望在一个简单的TextBlock中显示接收到的字节,这与上面的代码一样在MainPage上,但是当我在foreach循环中编写MyTextBlock.Text = b.ToString()时,Visual会引发一个访问冲突异常。我在BLE_Function()中使用相同的BLE_Function,在那里它工作得很好,所以我不明白为什么不能从temperatureMeasurementChanged函数访问它。下面粘贴的是例外详细信息:
System.UnauthorizedAccessException未被用户代码处理 HResult=-2147024891 Message=Invalid跨线程访问. Source=System.Windows System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp的MS.Internal.XcpImports.CheckThread(),PhoneApp2.MainPage.temperatureMeasurementChanged(GattCharacteristic发件人( GattValueChangedEventArgs args)的PhoneApp2.MainPage.displayText(拜特数据)的对象值,布尔值( allowReadOnlySet) InnerException:
提前谢谢。
发布于 2014-12-06 13:28:14
引发异常是因为您试图从另一个线程更新GUI,而不是GUI线程。您必须使用Dispatcher.BeginInvoke()来更新GUI。您可以找到一个示例这里。
https://stackoverflow.com/questions/27332047
复制相似问题