0

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

该应用程序很少执行,但在进行一些更改后停止响应。


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( ) 在几次试验后停止执行。这是无法预料的行为。

4

1 回答 1

0

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

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

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();
}
于 2013-10-29T08:40:50.103 回答