从计时器线程更新WPF UI [英] WPF UI update from a timer thread
问题描述
在App内,我显示随时间推移或当用户单击下一个/上一个时旋转的横幅。
Within the App I display banners that rotate as time progresses or when user clicks next/previous.
1)我需要更新<$ c内的UI元素$ c> Timer.Elapsed 方法。从我发现的结果来看,计时器滴答似乎是在自己的线程上执行的,应该使用元素的分派器来更新UI。
1) I need to update an UI element within Timer.Elapsed
method. 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.
( (Image)BannerPanel.Content ).Dispatcher.Invoke( new Action( () => {
( (Image)BannerPanel.Content ).Source = GetImage( new Uri( banner.Uri, UriKind.Absolute ) );
} ) );
,但这会引发 InvalidOperationException
。
2)标语控制器提供 Next
和 Previous
方法,其中,当被称为分别显示下一个/上一个横幅时。由于 DisplayBanner
方法尝试显示横幅,当找不到文件时,它尝试使用 WebClient
重新下载它s AsyncFileDownload
并在 DownloadComplete
上显示图像。我是否正确地假设计时器触发了逝去的
和手动调用 Next
/ 上一个
可以同时发生,都在各自的线程上运行(上一个
/ 下一个
在UI线程上,并且 Elapsed
在计时器线程上),是否可能导致不稳定?
2) The banner controller provides Next
and Previous
methods, which, when called display next/previous banner respectively. 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. 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?
推荐答案
您应该研究使用 DispatcherTimer
类,而不是常规的 Timer
。它设计用于WPF UI,仅用于这些类型的使用,因为它运行在 Dispatcher
线程上。
You should look into using the DispatcherTimer
class instead of a regular Timer
. It's designed to be used with WPF UI for just these types of uses because it runs on the Dispatcher
thread.
更多信息:系统。 Windows.Threading.DispatcherTimer
这篇关于从计时器线程更新WPF UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!