2014-12-06 33 views
0

我通过蓝牙从外部设备接收一些数据,并且我有一个事件处理程序,只要收到数据就会触发。这是一个非常基本的应用,在那里我有主网页当被按下时,执行以下功能上的按钮:无法访问Windows Phone 8中的TextBlock属性

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 Studio引发了访问冲突异常。我在BLE_Function()中使用了相同的TextBlock,并且在那里工作正常,所以我不明白为什么我无法通过temperatureMeasurementChanged函数访问它。下面粘贴有异常的详细信息:

System.UnauthorizedAccessException的是由用户代码
的HResult = -2147024891
消息=无效跨线程访问未处理。
源= 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参数)
的InnerException:

提前致谢。

回答

1

由于您试图从GUI线程以外的其他线程更新GUI,因此引发异常。您必须使用Dispatcher.BeginInvoke()来更新GUI。你可以找到一个例子here

+0

谢谢,这工作,但如果这是一个线程问题,我不明白我能够直接从异步BLE_Function访问TextBlock,但不是从偶处理函数? – Ali250 2014-12-06 13:37:54

+0

这是因为BLE_Function在GUI线程上,而事件处理程序位于单独的线程上,因为它是异步调用的。 – venerik 2014-12-06 13:45:48