Bob,
In addition to the other comments.
Remember when windows schedules your thread it looks at 2 main items:
Timeslice & Priority.
If your thread is a higher priority then other threads it will get most of
the timeslices. Thread.Sleep(0) gives lower priority threads a quicker
chance to run. (Windows does temporarily adjust priorities so all the lower
priority threads are not totally starved).
A Timeslice is some fraction of a second (lets say 100 ms) that windows
allows your thread to run. If each loop iteration in your thread takes only
10 ms, you can call Thread.Sleep(0) to give 90 ms (the reminder of your
timeslice) to the next thread that is available to run. Without the
Thread.Sleep(0) your thread would process 10 iterations before relinquishing
control. Depending on what you are doing this may cause an overall
sluggishness to the computer.
Sleep(0) is also useful if you are polling a resource, such as a shared
field where one thread sets it and a second thread reads it. With Sleep(0)
the second thread can give up its timeslice to the first thread, allowing
the first thread to finish calculating & setting the value. Rather then be
in a "tight" loop checking to see if the field changed. However! I would
normally use a ManualResetEvent or AutoResetEvent instead of Sleep(0), as
they are friendlier.
Hope this helps
Jay
"Bob Day" <Bo****@TouchTalk.net> wrote in message
news:ur**************@TK2MSFTNGP10.phx.gbl...
Yes, I agree and understand that. But wouldn't that happen automatically
anyway? In other words, should you put.Sleep(0) through out various
threads to allow other threads to run? I know the anwser to that is no, so if it
happens automatically, what is the point of putting it in manually as
.Sleep(0)?
Thanks!
Bob Day
"Tom Shelton" <to*@YOUKNOWTHEDRILLmtogden.com> wrote in message
news:uw**************@TK2MSFTNGP12.phx.gbl... In article <OP**************@TK2MSFTNGP11.phx.gbl>, Bob Day wrote: Using VS 2003, VB.net, MSDE...
I have seen some sample programs use the following line to yield a
time slice to other threads:
Thread.CurrentThread.Sleep(0)
The line does not produce a error, but I don't follow why it would be needed or when it would be needed.
Please advise.
Bob Day
It's in the docs... A value of 0 tells the OS to suspend the thread in
favor of other waiting threads. Basically, you're saying to the OS, I'm
done for now, give someone else the rest of my time-slice.
--
Tom Shelton [MVP]