Windows Phone计时器间隔不一致
我期待使用C#创建Windows Phone应用程序。我想要一个计时器,显示一个图像100毫秒,然后切换到另一个图像,然后再等待900毫秒,然后再次闪烁图像。我有下面的代码编写,但是,它似乎并不一致。有任何想法吗?Windows Phone计时器间隔不一致
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();
}
}
我不是一个winforms/wpf/silverlight家伙,但我会说你需要使你的窗口无效。
调用任何需要刷新渲染方法,因为我觉得改变源图像不触发刷新
的DispatchTimer文件说:
定时器都不能保证执行恰好在时间间隔发生时,但它们保证在时间间隔发生之前不执行。这是因为DispatcherTimer操作像其他操作一样放在Dispatcher队列中。执行DispatcherTimer操作时,依赖于队列中的其他作业及其优先级。
我不知道这是什么原因导致您的问题,因为我从未与DispatchTimer
合作过。
您还有其他的计时器选项。例如,您可以使用System.Timers.Timer
或System.Threading.Timer
(我推荐使用System.Timers.Timer
)。但请注意,如果您使用其中一个定时器,回调将在池线程上执行,您需要同步对UI线程的访问。再次从DispatchTimer
文档:
如果System.Timers.Timer在WPF应用程序使用时,值得注意的是,System.Timers.Timer在不同的线程,则用户界面(UI)的线程中运行。为了访问用户界面(UI)线程上的对象,必须使用Invoke或BeginInvoke将操作发布到用户界面(UI)线程的分派器上。使用与System.Timers.Timer相对的DispatcherTimer的原因是DispatcherTimer与Dispatcher在同一个线程上运行,并且可以在DispatcherTimer上设置DispatcherPriority。
您可能会考虑增加计时器的优先级?
在这种情况下,“不一致”是什么意思?图像是否会闪烁一次,然后再次不会再闪烁?它熬夜还是短于100毫秒?另外,您可能会考虑更改操作顺序。停止计时器,设置间隔,然后重新启动计时器。尽管如此,我认为你可以在不停止/重新启动的情况下设置时间间隔。 – 2011-12-29 07:28:53
不一致的是,图像显示的时间不会真正为100ms,并且不会每次都真正等待900ms。我会尝试设置间隔而不停止并重新启动。 – zaber76 2011-12-29 13:09:09
我可以真正注意到的是,当我在这段代码中放置一行代码以播放点击型mp3文件时,我真的注意到有些东西不对:if(current> = files.Count) { current = 0; 012.Interval = TimeSpan.FromMilliseconds(100); timer.Stop(); timer.Start(); } 我连续多次听到声音“咔哒”一声,而其他时间只听到一次。但绝对不一致。几乎听起来像有多个计时器。 – zaber76 2011-12-29 14:12:32