我正在寻找使用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();
}
}
答案 0 :(得分:3)
DispatchTimer文档说:
不保证定时器在时间间隔发生时准确执行,但保证在时间间隔发生之前不执行定时器。这是因为DispatcherTimer操作与其他操作一样放在Dispatcher队列中。 DispatcherTimer操作执行时依赖于队列中的其他作业及其优先级。
我不知道这是否是导致您出现问题的原因,因为我从未与DispatchTimer
合作过。
您还有其他计时器选项。例如,您可以使用System.Timers.Timer
或System.Threading.Timer
(我建议使用System.Timers.Timer
)。但请注意,如果您使用其中一个计时器,则回调将在池线程上执行,您需要同步对UI线程的访问。再次来自DispatchTimer
文档:
如果在WPF应用程序中使用System.Timers.Timer,则值得注意的是System.Timers.Timer在与用户界面(UI)线程不同的线程上运行。为了访问用户界面(UI)线程上的对象,必须使用Invoke或BeginInvoke将操作发布到用户界面(UI)线程的Dispatcher上。使用与System.Timers.Timer相对的DispatcherTimer的原因是DispatcherTimer在与Dispatcher相同的线程上运行,并且可以在DispatcherTimer上设置DispatcherPriority。
您可以考虑提高计时器的优先级吗?
答案 1 :(得分:0)
我不是一个winforms / wpf / silverlight家伙,但我会说你需要让你的窗口无效。
调用刷新渲染所需的任何方法,因为我认为更改源图像不会触发刷新