我正在创建一个Windows 8.1 Phone应用程序。 UI有一个按钮和一个TextBox(称为txtStatus)
基本上,当我点击用户界面中的某个按钮时,以下代码将启动(仅显示部分代码):
private async void btnStart_Click(object sender, RoutedEventArgs e)
{
try
{
// Get the list of Microsoft Bands paired to the phone.
IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
if (pairedBands.Length < 1)
{
txtStatus.Text = "This sample app requires a Microsoft Band paired to your device. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
return;
}
// Connect to Microsoft Band.
using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
{
bandClient.SensorManager.HeartRate.ReadingChanged += HeartRate_ReadingChanged;
await bandClient.SensorManager.HeartRate.StartReadingsAsync();
// Receive Accelerometer data for a while, then stop the subscription.
await Task.Delay(TimeSpan.FromSeconds(50));
await bandClient.SensorManager.HeartRate.StopReadingsAsync();
}
}
catch (Exception ex)
{
}
private void HeartRate_ReadingChanged(object sender, Microsoft.Band.Sensors.BandSensorReadingEventArgs<Microsoft.Band.Sensors.IBandHeartRateReading> e)
{
txtStatus.Text = string.Format("Current Heart Rate is: {0}", e.SensorReading.HeartRate.ToString());
}
当我运行此代码时,它会在处理程序中的以下行barfs:
txtStatus.Text = string.Format("Current Heart Rate is: {0}", e.SensorReading.HeartRate.ToString());
异常消息如下:
该应用程序调用了一个为a编组的接口 不同的线程。 (HRESULT的例外情况:0x8001010E (RPC_E_WRONG_THREAD))
听起来像UI线程和传感器读取线程不同。关于如何为两者使用相同线程的任何建议。或者如何在两个线程之间传递数据?
感谢您的期待。
答案 0 :(得分:5)
该事件是在后台线程上引发的。使用CoreDispatcher.RunAsync
将其封送回UI线程:
private async void HeartRate_ReadingChanged(object sender, Microsoft.Band.Sensors.BandSensorReadingEventArgs<Microsoft.Band.Sensors.IBandHeartRateReading> e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
txtStatus.Text = string.Format("Current Heart Rate is: {0}", e.SensorReading.HeartRate.ToString())
}).AsTask();
}