Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF UI update from a timer thread

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?

like image 757
pikausp Avatar asked Feb 14 '26 05:02

pikausp


2 Answers

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

like image 51
toadflakz Avatar answered Feb 15 '26 18:02

toadflakz


Try using Application instead,

Application.Current.Dispatcher.Invoke(new Action(() => 
{
    ((Image)BannerPanel.Content).Source = GetImage(new Uri(banner.Uri, UriKind.Absolute));
});
like image 26
d.moncada Avatar answered Feb 15 '26 17:02

d.moncada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!