gpt4 book ai didi

c# - Band 应用程序调用了为不同线程编码的接口(interface)

转载 作者:行者123 更新时间:2023-12-02 17:32:21 29 4
gpt4 key购买 nike

我正在创建一个 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 线程和 Sensor 读取线程是不同的。有关如何对两者使用同一线程的任何建议。或者说如何在两个线程之间传递数据?

感谢期待。

最佳答案

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

关于c# - Band 应用程序调用了为不同线程编码的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211177/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com