1

I want to change the image source cyclically in my program, it's the C# code:

private void Img_MouseLeave(object sender, MouseEventArgs e)
{
    Image image = sender as Image;
    int milliseconds = 500;
    for(int i = 0; i < ImageUris.Count(); i++)
    {
       Thread.Sleep(milliseconds);
       image.Source = new BitmapImage(new Uri(@ImageUris[i], UriKind.Absolute));
    }
}

But the problem is when I run my program the window is freezed. There is no happen in the window. I think maybe it's affected by thread, but I can't find a way do it.

0

1 Answer 1

3

The call Thread.Sleep will freeze the MainThread that is running your application.

Use a DispatcherTimer to avoid freezing your application.

DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 500);

private void dispatcherTimer_Tick(object sender, EventArgs e) {
   // assign new source to the Image
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.