Windows Phone定时器间隔不一致

本文关键字:不一致 定时器 Phone Windows | 更新日期: 2023-09-27 18:19:04

我希望使用c#创建一个windows phone应用程序。我想有一个计时器,显示一个图像100毫秒,然后切换到另一个图像,然后等待另一个900毫秒之前,它再次闪烁图像。我已经写了下面的代码,然而,它似乎不始终闪烁。什么好主意吗?

public partial class MainPage : PhoneApplicationPage
{
    DispatcherTimer timer = new DispatcherTimer();
    List<string> files = new List<string>() { "Images/off-light.png", "Images/on-light.png" };
    List<BitmapImage> images = new List<BitmapImage>();
    int current = 0;
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        foreach (string file in files)
        {
            BitmapImage image = new BitmapImage(new Uri(file, UriKind.Relative));
            images.Add(image);
        }

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(900);
            timer.Tick += new EventHandler(timer_Tick);
    }
    void timer_Tick(object sender, EventArgs e)
    {
        myImage.Source = images[current];
        current++;
        if (current >= files.Count)
        {
            current = 0;
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Stop();
            timer.Start();
        }
        else
        {
            timer.Interval = TimeSpan.FromMilliseconds(900);
            timer.Stop();
            timer.Start();
        }
    }
    private void btnStop_Click(object sender, RoutedEventArgs e)
    {
        timer.Stop();
        myImage.Source = images[0];
    }
    private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        timer.Start();
    }
}

Windows Phone定时器间隔不一致

DispatchTimer文档说:

定时器不保证正好在时间间隔发生的时候执行,但可以保证在时间间隔发生之前不执行。这是因为DispatcherTimer操作像其他操作一样放在Dispatcher队列上。DispatcherTimer操作何时执行取决于队列中的其他作业及其优先级。

我不知道这是否是导致你的问题的原因,因为我从未与DispatchTimer合作过。

您确实有其他定时器选项。例如,您可以使用System.Timers.TimerSystem.Threading.Timer(我推荐使用System.Timers.Timer)。但是请注意,如果您使用这些计时器之一,则回调将在池线程上执行,并且您需要同步对UI线程的访问。同样来自DispatchTimer文档:

如果在WPF应用程序中使用了System.Timers.Timer,值得注意的是System.Timers.Timer在不同的线程上运行,而不是在用户界面(UI)线程上运行。为了访问用户界面(UI)线程上的对象,有必要使用Invoke或BeginInvoke将操作发布到用户界面(UI)线程的Dispatcher上。使用DispatcherTimer而不是System.Timers.Timer的原因是DispatcherTimer与Dispatcher运行在同一个线程上,并且DispatcherPriority可以在DispatcherTimer上设置。

你可以考虑增加定时器的优先级吗?

我不是一个winforms/wpf/silverlight家伙,但我想说你需要使你的窗口无效。

调用刷新渲染所需的任何方法,因为我认为更改源图像不会触发刷新