【发布时间】:2015-02-04 13:50:48
【问题描述】:
我正在通过蓝牙从外部设备接收一些数据,并且我有一个事件处理程序,它会在收到数据时触发。这是一个非常基本的应用程序,我在主页上有一个按钮,按下该按钮时会执行以下功能:
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 上,就像上面的代码一样,但是当我写 MyTextBlock.Text = b.ToString() 在 foreach 循环中,Visual Studio 引发访问冲突异常。我在 BLE_Function() 中使用了相同的 TextBlock,并且在那里它工作正常,所以我不明白为什么我不能从 temperatureMeasurementChanged 函数访问它。下面粘贴的是异常详细信息:
System.UnauthorizedAccessException 未被用户代码处理
HResult=-2147024891
Message=无效的跨线程访问。
源=System.Windows
堆栈跟踪: 在 MS.Internal.XcpImports.CheckThread() 在 System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp,对象值,布尔值 allowReadOnlySet) 在 System.Windows.Controls.TextBlock.set_Text(字符串值) 在 PhoneApp2.MainPage.displayText(字节数据) 在 PhoneApp2.MainPage.temperatureMeasurementChanged(GattCharacteristic 发件人,GattValueChangedEventArgs 参数)
内部异常:
提前致谢。
【问题讨论】:
标签: c# visual-studio windows-phone-8