C#秒表类不精确

时间:2017-03-09 09:28:49

标签: c# android xamarin xamarin.android

我在VS中开发了非常简单的Android应用程序。基本上我有2个标签(textviews)和1个按钮。逻辑是当我按下按钮秒表开始和按下下一次按钮秒表停止,计算已经过了多少时间并重新启动秒表。

        Button takt = FindViewById<Button>(Resource.Id.takt);

        Stopwatch st = new Stopwatch();

        TextView vv = (TextView)FindViewById(Resource.Id.textView1);
        TextView aavv = (TextView)FindViewById(Resource.Id.textView2);

        long bpm = 0;

        takt.Click += delegate {
            if(st.ElapsedMilliseconds != 0) // so avoiding division by zero
            {
                bpm = 60000 / st.ElapsedMilliseconds;
                vv.Text = st.ElapsedMilliseconds + " ms";
                aavv.Text = bpm + " BPM";

            }

            st.Restart();

        };

所以当我开始按下按钮时,秒表开始表现得很奇怪。有时它显示250ms下一次280ms然后它跳跃到500ms但是攻丝几乎是恒定的(变化250-270ms)。问题是为什么那些跳跃发生并且有没有办法没有跳跃?

编辑:

        Button takt = FindViewById<Button>(Resource.Id.takt);
        TextView avgBPM = (TextView)FindViewById(Resource.Id.textView1);    
        TextView BPM = (TextView)FindViewById(Resource.Id.textView2);
        Button reset = FindViewById<Button>(Resource.Id.button1);

        Stopwatch st = new Stopwatch();

        long bpm = 0;
        long sum = 0;
        long divide = 0;
        double avg = 0.0;

        avgBPM.Text = "Avg BMP: " + avg;
        BPM.Text = bpm + " BPM";

        takt.Click += delegate
        {
            st.Stop();
            if (st.ElapsedMilliseconds != 0)
            {
                divide++;
                bpm = 60000 / st.ElapsedMilliseconds;
                sum += bpm;
                avg = sum / divide;
                avgBPM.Text = "Avg BMP: " + avg;
                BPM.Text = bpm + " BPM";

            }

            st.Reset();
            st.Start();

        };
        reset.Click += delegate
        {
            bpm = 0;
            sum = 0;
            divide = 0;
            avg = 0;
            st.Stop();
            st.Reset();

            avgBPM.Text = "Avg BMP: " + avg;
            BPM.Text = bpm + " BPM";


        };

我已经改变秒表现在它在计算之前停止,做所有的事情,然后重新启动秒表。添加了averageBPM文本,现在它显示了精确的平均值。现在我需要帮助如何在另一个线程中更改UI。我尝试创建新函数 void change(),但我无法在该函数中看到textviews。

0 个答案:

没有答案