locked
求助,多线程下的振动器 VibrateController 关不掉 RRS feed

  • 问题

  • 有2个按钮 btnStart,点击后启动振动器; btnStop 点击后停止震动

    当我连续点击btnStart的时候 会多次启动多个线程同时震动 ,而此时点击btnStop失效。

    具体代码如下,请老师帮忙看看

    public class VibrateHelper
        {
            private bool IsVibrated = false;
            private bool IsCustomVibrated = false;

            public int VibrateTime { get; set; }
            public int VibrateStopTime { get; set; }

            public void Start()
            {
                this.IsVibrated = true;
                Thread t = new Thread(new ThreadStart(AsyncVibrate));
                t.Start();
            }

            public void StartCustomVibrate()
            {
                this.IsCustomVibrated = true;
                Thread thread = new Thread(new ThreadStart(AsyncCustomVibrate));
                thread.Start();
            }
            private void AsyncCustomVibrate()
            {
                while (this.IsCustomVibrated)
                {
                    this.Start();
                    Thread.Sleep(VibrateTime);
                    this.stop();
                    Thread.Sleep(VibrateStopTime);
                }
            }

            public void stop()
            {
                this.IsVibrated = false;
                Microsoft.Devices.VibrateController.Default.Stop();
            }

            public void CustomVibrateStop()
            {
                this.IsCustomVibrated = false;
                this.IsVibrated = false;
                Microsoft.Devices.VibrateController.Default.Stop();
            }

            private void AsyncVibrate()
            {
                while (this.IsVibrated)
                {
                    Microsoft.Devices.VibrateController.Default.Start(TimeSpan.FromMilliseconds(2000));
                    Thread.Sleep(5);
                }
            }
        }

    MainPage:

    VibrateHelper vb = new VibrateHelper();

     private void btnStart_Click(object sender, RoutedEventArgs e)
            {
                vb.VibrateTime = int.Parse(this.txtVibrate.Text);
                vb.VibrateStopTime = int.Parse(this.txtStop.Text);
                vb.StartCustomVibrate();
            }

            private void btnStop_Click(object sender, RoutedEventArgs e)
            {
                vb.stop();
                vb.CustomVibrateStop();
            }

    2015年1月2日 9:18

全部回复

  • up up  up
    2015年1月3日 9:10
  • 你好,

    我这边在真机上测试了你的代码,发现多次点击开始按钮后,点击停止按钮就可以停止震动,不清楚你的问题,可以再描述清楚重现步骤吗?

    我的VibrateTime为10,VibrateStopTime为3


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2015年1月5日 8:46
    版主