Thread.Sleep() in C#

后端 未结 4 636
孤街浪徒
孤街浪徒 2020-12-06 20:31

I want to make an image viewer in C# Visual Studio 2010 which displays images one by one after seconds:

i = 0;

if (image1.Length > 0) //image1          


        
相关标签:
4条回答
  • 2020-12-06 20:54

    If you want to avoid using Timer and defining an event handler you can do this:

    DateTime t = DateTime.Now;
    while (i < image1.Length) {
        DateTime now = DateTime.Now;
        if ((now - t).TotalSeconds >= 2) {
            pictureBox1.Image = Image.FromFile(image1[i]);
            i++;
            t = now;
        }
        Application.DoEvents();
    }
    
    0 讨论(0)
  • 2020-12-06 21:01

    Thread.Sleep blocks your UI thread use System.Windows.Forms.Timer instead.

    0 讨论(0)
  • 2020-12-06 21:01

    Yes, because Thread.Sleep blocks the UI thread during the 2s.

    Use a timer instead.

    0 讨论(0)
  • 2020-12-06 21:09

    Use a Timer.

    First declare your Timer and set it to tick every second, calling TimerEventProcessor when it ticks.

    static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    myTimer.Tick += new EventHandler(TimerEventProcessor);
    myTimer.Interval = 1000;
    myTimer.Start();
    

    Your class will need the image1 array and an int variable imageCounter to keep track of the current image accessible to the TimerEventProcessor function.

    var image1[] = ...;
    var imageCounter = 0;
    

    Then write what you want to happen on each tick

    private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) {
        if (image1 == null || imageCounter >= image1.Length)
            return;
    
        pictureBox1.Image = Image.FromFile(image1[imageCounter++]);
    }
    

    Something like this should work.

    0 讨论(0)
提交回复
热议问题