Search code examples
c#gifpicturebox

Showing a lot of picturebox in a form and playing gif, causes the form and gifs to freeze


I try to write an application with a large number of GIF animations in a form (30-40 picture boxes and each .gif image is 200-500kb). However, when I use so much Picturebox and run the program, the form freezes too much, and the gif animations that normally need to pass to the next image in 100MS, move to the next image within 5-6 seconds. How to handle this situation. Thank you

I tried to show pictures ,in gif, one by one that way but i had same result

 public class Class1 : PictureBox
    {
   
        public Class1()
        {
       
      
        }

     
       
        public Image[] imagelist { get; set; } = new Image[10];
    
        public int currentimage;
        private int imagecount = 1;

        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            this.Image = imagelist[0];
            imagecount = imagelist.TakeWhile(r => r != null).Count();
        }

        public void NextImage()
        {
            currentimage = (currentimage + 1) % imagecount;
            this.Image = imagelist[currentimage];
        }
    }



public Form1()
        {
            InitializeComponent();
            array = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                .Where(f => f.GetValue(this) != null&&f.FieldType == typeof(Class1)).Select(f => f.GetValue(this)).Cast<Class1>().ToArray();
            Thread = new Thread(Start);
            Thread.Start();
        }

        private Thread Thread;
        private void Start()
        {
            Thread.Sleep(400);
            while (true)
            {
                this.Invoke((MethodInvoker)(() =>
               {
                   foreach (Class1 class1 in array)
                   {
                       class1.NextImage();
                   }
               }));
                Thread.Sleep(100);
            }
        }

Solution

  • Use 'BeginInvoke' instead 'Invoke'. Invoke makes your ui wait until action finished and it will make your app not responding or slow. Use 'BeginInvoke' often in windows apps.

    or

    I think it's because your pictures has different size than your picturebox or has different w/h ratio from picturebox so it had to calculate the streching and takes time. So you can do

    • if your picturebox has const width and height, resize your image or gif with same size with picturebox
    • or change to normal and not do any change on picturebox sizemode