Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Sleep() in C#

Tags:

c#

winforms

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 is an array string containing the images directory
{
    while (i < image1.Length)
    {
        pictureBox1.Image = System.Drawing.Image.FromFile(image1[i]);
        i++;
        System.Threading.Thread.Sleep(2000);
    }

When the program starts, it stops and just shows me the first and last image.

like image 724
Alyafey Avatar asked Aug 20 '12 14:08

Alyafey


People also ask

What's thread sleep () in threading?

Suspends the current thread for the specified number of milliseconds.

How long is thread sleep 1000?

sleep time means more than what you really intended. For example, with thread. sleep(1000), you intended 1,000 milliseconds, but it could potentially sleep for more than 1,000 milliseconds too as it waits for its turn in the scheduler. Each thread has its own use of CPU and virtual memory.

Is sleep () a system call?

The sleep system call is used to take a time value as a parameter, specifying the minimum amount of time that the process is to sleep before resuming execution. This method is used to sleep a thread for a specified amount of time.

What is wait () and sleep () in OS?

The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. This was just a clear and basic explanation, if you want more than that then continue reading.


2 Answers

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

like image 74
L.B Avatar answered Oct 24 '22 21:10

L.B


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.

like image 25
CaffGeek Avatar answered Oct 24 '22 21:10

CaffGeek