在几个触发器之后,Accelerometer事件处理程序不响应。 WP8

时间:2013-10-29 04:56:44

标签: windows-phone-8 accelerometer

我正在构建用于在文本块上读取和显示x,y和z值的Windows应用程序。

该应用程序几乎不执行,但在几次更改后停止响应。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp9.Resources;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;

namespace PhoneApp9
{
  public partial class MainPage : PhoneApplicationPage
 {
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Accelerometer acc = new  Accelerometer();
       acc.CurrentValueChanged  +=acc_ReadingChanged;

        try
        {
            acc.Start();
        }

        catch(Exception ex)
        {
            tbk.Text = ex.ToString();
        }


    }

    private void acc_ReadingChanged(object sender,                   SensorReadingEventArgs<AccelerometerReading> e)
    { 

        try
        {
            System.Threading.Thread.Sleep(1);
              Dispatcher.BeginInvoke( () =>
            {

                      tbk.Text = "X:" + e.SensorReading.Acceleration.X.ToString("0.00");
                      tbk.Text += "\nY:" + e.SensorReading.Acceleration.Y.ToString("0.00");
                      tbk.Text += "\nZ:" + e.SensorReading.Acceleration.Z.ToString("0.00");

                    });


        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        //throw new NotImplementedException();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        if (Accelerometer.IsSupported==true)
            MessageBox.Show("exist");
        else
            MessageBox.Show("not exïst");


    }



   }
 }
}

handler()在几次试用后停止执行。这是未经预测的行为。

1 个答案:

答案 0 :(得分:0)

为什么使用System.Threading.Thread.Sleep(1)??

Dispatcher.BeginInvoke将事件添加到UI事件循环。也许加速度计更新比ui事件循环执行更快。因此,ui eventloop会增长,几秒钟后您的应用程序就会被阻止。你可以尝试添加一个布尔值来控制它。

bool displaySensorData = false;
private void acc_ReadingChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{ 
    if(displaySensorData ) return;
    try
    {
        displaySensorData = true;
        Dispatcher.BeginInvoke( () =>
        {

            tbk.Text = "X:" + e.SensorReading.Acceleration.X.ToString("0.00");
            tbk.Text += "\nY:" + e.SensorReading.Acceleration.Y.ToString("0.00");
            tbk.Text += "\nZ:" + e.SensorReading.Acceleration.Z.ToString("0.00");
            displaySensorData = false;

        });
    }
    catch (Exception ex)
    {
        displaySensorData = false;
        MessageBox.Show(ex.ToString());
    }
    //throw new NotImplementedException();
}