Reputation: 1049
I need to load each second (or two) new image.
Following code doesn't work:
System.Threading.Thread.Sleep(2000);
this.Image_LoadImage.Source = new BitmapImage(new Uri(@"D:\\connect2-1.gif"));
System.Threading.Thread.Sleep(2000);
this.Image_LoadImage.Source = new BitmapImage(new Uri(@"D:\\connect3-1.gif"));
What I see is that the app sleeps for 4 seconds and then the second image appears.
How can i do it? Thanks.
Upvotes: 2
Views: 2612
Reputation: 23266
Use timer for this
private System.Threading.Timer timer;
public MainWindow()
{
InitializeComponent();
timer = new System.Threading.Timer(OnTimerEllapsed, new object(), 0, 2000);
}
private void OnTimerEllapsed(object state)
{
if (!this.Dispatcher.CheckAccess())
{
this.Dispatcher.Invoke(new Action(LoadImages));
}
}
private bool switcher;
private void LoadImages()
{
string stringUri = switcher ? @"D:\\connect2-1.gif" :
@"D:\\connect3-1.gif";
this.Image_LoadImage.Source = new BitmapImage(new Uri(stringUri));
switcher = !switcher;
}
Upvotes: 5
Reputation: 8520
I suppose that your code resides in a single function, which executes on the main thread. For this reason, the UI will not be updated until your function returns.
At that point, you'll be left with whatever state was the latest at the time your function returned (this is why you're only seeing the last picture you've set).
Also, note that by issuing a Sleep()
request mid-function, you're essentially blocking the main thread of your application (or whatever thread your function is running in, but it's likely that this is your main thread). During sleep time, your application won't simply respond to anything and your UI will freeze.
You might decide to invalidate your controls (Control.Refresh()
, Control.Invalidate()
, Control.Update()
, Control.Refresh()
, Application.DoEvents()
) but these are generally hacks unless used properly.
Using a Timer
is an option. Although, in your specific case, simply using an Animated GIF might be the best solution.
Note that if you decide to use a timer there is quite an important difference between System.Windows.Forms.Timer
and other timers. System.Windows.Forms.Timer
will run on your main thread at the earliest convenience (and so, it will be safe to interact with UI controls because you will be doing so from the same thread; but, on the other hand, it might fire with a slight delay). If, instead, you're going to use a different timer, you will not be able to access UI controls directly without violating an important rule. More about that here: Comparing the Timer Classes in the .NET Framework Class Library
See: Force GUI update from UI Thread
And: Animated Gif in form using C#
Upvotes: 3