WPF UI update from a timer thread

做~自己de王妃 提交于 2019-12-11 06:46:12

问题


Within the App I display banners that rotate as time progresses or when user clicks next/previous.

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 ) );
} ) );

but that throws an InvalidOperationException.

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?


回答1:


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.

More info: System.Windows.Threading.DispatcherTimer




回答2:


Try using Application instead,

Application.Current.Dispatcher.Invoke(new Action(() => 
{
    ((Image)BannerPanel.Content).Source = GetImage(new Uri(banner.Uri, UriKind.Absolute));
});


来源:https://stackoverflow.com/questions/25669010/wpf-ui-update-from-a-timer-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!