Band 应用程序调用了一个为不同线程编组的接口

The Band application called an interface that was marshalled for a different thread

我正在创建一个 Windows 8.1 Phone 应用程序。 UI 有一个按钮和一个文本框(称为 txtStatus)

基本上,当我单击 UI 中的一个按钮时,以下代码开始运行(仅显示其中的一部分):

 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());
        }

当我 运行 这段代码时,它会在处理程序中的以下行中吐出:

txtStatus.Text = string.Format("Current Heart Rate is: {0}", e.SensorReading.HeartRate.ToString());

异常信息如下:

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

听起来 UI 线程和传感器读取线程不同。关于如何对两者使用相同线程的任何建议。或者如何在两个线程之间传递数据?

感谢期待。

事件在后台线程上引发。使用 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();
}