ckv
ckv

Reputation: 10820

What does Thread.Sleep(0) mean C#?

Does mean there is no delay?

A book says the below **

Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.

**

Does it mean that even though a statement is supposed to be executed, giving 0 for sleep will skip execution for the moment?

Upvotes: 2

Views: 3138

Answers (5)

Dezmen Ceo Sykes
Dezmen Ceo Sykes

Reputation: 301

It could be like

bool isRunning;

public void Main
{
    Thread t = new Thread(Method);
    t.Start();
    isRunning = true;
}

public void Method(int i)
{
    while(isRunning)
    {
        i = 0;
        i++;
        Thread.Sleep(0);
        Console.WriteLine(i);
    }
}

Upvotes: -4

AllTooSir
AllTooSir

Reputation: 49362

With Thread.Sleep(0) your code is suspended for a single cycle and then scheduled for the next available slot.

Upvotes: -1

Jerry Coffin
Jerry Coffin

Reputation: 490048

The 0 means there's no minimum period of time before which control will be returned to the thread. If there are any other threads ready to run at the moment, however, they're likely to be scheduled, so your thread will sleep some non-zero period of time.

The same is true with any other time period you specify -- Sleep(N) means it should sleep a minimum of the specified time, but may sleep some arbitrarily greater length of time.

At the same time, Sleep(0) does mean that if there's no other thread ready to run, control can/will be returned to your thread immediately.

Upvotes: 6

p.s.w.g
p.s.w.g

Reputation: 148980

It allows the operating system to continue processing any other threads that might be waiting. The next statement will be executed as soon as the current thread resumes—which might be immediately, or after some time, when the other thread(s) yield.

Upvotes: 2

mcmonkey4eva
mcmonkey4eva

Reputation: 1377

It means that you will allow other processes to run their code, but also try to continue your own code as soon as possible.

Upvotes: 1

Related Questions