[英]WPF UI update from a timer thread
Within the App I display banners that rotate as time progresses or when user clicks next/previous. 在App I中,显示随时间推移或用户点击下一个/上一个时旋转的横幅。
1) I need to update an UI element within Timer.Elapsed
method. 1)我需要更新
Timer.Elapsed
方法中的UI元素。 From what I found, it seems that timer ticks are executed on their own thread and element's dispatcher should be use to update the UI. 根据我的发现,似乎计时器滴答在他们自己的线程上执行,元素的调度程序应该用于更新UI。
( (Image)BannerPanel.Content ).Dispatcher.Invoke( new Action( () => {
( (Image)BannerPanel.Content ).Source = GetImage( new Uri( banner.Uri, UriKind.Absolute ) );
} ) );
but that throws an InvalidOperationException
. 但是会抛出
InvalidOperationException
。
2) The banner controller provides Next
and Previous
methods, which, when called display next/previous banner respectively. 2)横幅控制器提供
Next
和Previous
方法,分别称为显示下一个/上一个横幅。 As DisplayBanner
method tries to display banner and when the file is not found it tries to re-download it using WebClient
's AsyncFileDownload
and on DownloadComplete
it displays the image. 当
DisplayBanner
方法尝试显示横幅时,当找不到文件时,它会尝试使用WebClient
的AsyncFileDownload
重新下载它,而在DownloadComplete
它会显示图像。 Am I correct to assume that both, Elapsed
fired by the timer and manual call of Next
/ Previous
can occure at the same time, both being run on their own thread ( Previous
/ Next
on UI thread and Elapsed
on Timer thread ), possibly causing instability? 我是否正确假设两个,由定时器触发的
Elapsed
和Next
/ Previous
手动调用可以同时发生,两者都在他们自己的线程Previous
运行(UI线程上的上Previous
/ Next
和定时器线程上的Elapsed
),可能导致不稳定?
You should look into using the DispatcherTimer
class instead of a regular Timer
. 您应该考虑使用
DispatcherTimer
类而不是常规Timer
。 It's designed to be used with WPF UI for just these types of uses because it runs on the Dispatcher
thread. 它被设计为与WPF UI一起用于这些类型的用途,因为它在
Dispatcher
线程上运行。
More info: System.Windows.Threading.DispatcherTimer 更多信息: System.Windows.Threading.DispatcherTimer
Try using Application instead, 尝试使用Application,
Application.Current.Dispatcher.Invoke(new Action(() =>
{
((Image)BannerPanel.Content).Source = GetImage(new Uri(banner.Uri, UriKind.Absolute));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.