2

I have a timer and on every tick I want to take an image file from the hard drive and change the image that is being displayed in the Image with this piece if code

  Application.Current.Dispatcher.BeginInvoke(
            DispatcherPriority.Render,
            new Action(() => CameraImageBox.Source =
                             (ImageSource)new BitmapImage(new Uri(e.FileName))));

The Image control turns pitch black after a couple of dozen of images and the whole ui turns quite unresponsive. How can I avoid the black out and improve the performance over all?

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Sevki
  • 3,592
  • 4
  • 30
  • 53

2 Answers2

4

I tried your code in a dispatcher timer (100 milliseocnds delay) that iterates through hundreds of nice 800 * 680 size images at the same DispatcherPriority.Render.

public partial class Window3 : Window
{
    private int i = 0;

    private DispatcherTimer timer
      = new DispatcherTimer(DispatcherPriority.Render); 

    public Window3()
    {
        InitializeComponent();

        timer.Tick += new EventHandler(timer_Tick);
        timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
        timer.IsEnabled = true;
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        imgChanging.Source
             = (ImageSource)new BitmapImage(
                   new Uri("Images/Icon" + ((i++ % 100) + 1) + ".png",
                   UriKind.RelativeOrAbsolute));
     }
}  

My app seems to be running fine since last 10 minutes.It luks like something else is wrong in your code. Can you provide more details?

WPF-it
  • 19,625
  • 8
  • 55
  • 71
1

the Images dont get released after usage. You have to change the ChacheOption of the imagesource. Beside that you should use a DispatcherTimer in WPF.

DispatcherTimer:

    DispatcherTimer t = new DispatcherTimer();
    t.Interval = new TimeSpan(0, 0, 1);
    t.Tick +=new EventHandler(t_Tick);
    t.Start();

Set image:

private void SetImage(Uri loc)
    {
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() =>
            {

                BitmapImage  image = new BitmapImage();
                image.BeginInit();
                image.UriSource = loc;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.EndInit();
                imgDisplay.Source = image;
            }
            ));

    }
fixagon
  • 5,506
  • 22
  • 26